mobxjs / mobx

Simple, scalable state management.

Home Page:http://mobx.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

forceUpdate bug on observer components: "Warning: Cannot update a component (`X`) while rendering a different component (`X`)"

hasanayan opened this issue · comments

Intended outcome:
observer components should not force a re-render during a render

Actual outcome:
observer components are forcing re-render during a render

How to reproduce the issue:
I'm trying to integrate react-query and mobx using fromResource. Everything works fine except, when 2 different components consuming the same resource are mounted, the second once logs a warning (bad setState call warning). It is hard to explain throughly here but I created a public repo that showcases this pretty simply.

clone this repo: https://github.com/hasanayan/mobx-react-query

  • npm install
  • npm run dev
  • visit the app
  • click on one of the toggle buttons once
  • wait until the resouece is loaded (you'll see "Cool Entity" on screen)
  • click on the other toggle button once
  • check console, you will see the warning

Versions

"mobx": "^6.10.2",
"mobx-react": "^9.0.1",
"mobx-utils": "^6.0.8",
"@tanstack/react-query": "5.0.0-beta.20" (I believe this is irrelevant)

I think it's because repository.getEntity(3) is called during render and contains a side effect. That alone is problemantic - subscribing to resources etc should be done done in useEffect. It doesn't warn in the first case, because the side effect is async, but in the second case, the data are resolved immediately, so the sink is called during render. fromResouce doesn't care whether the value actually changed or not, so any time you call sink, it translates to setState on every component that is observing the resource.