mobxjs / mobx-react

React bindings for MobX

Home Page:https://mobx.js.org/react-integration.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using observer with react hooks does not work

barbalex opened this issue · comments

https://codesandbox.io/s/7z9yok8mn1

This error occurs:

Hooks can only be called inside the body of a function component.

There is already an issue for this (#591) but it was closed as the author wants to wait for a version of mobx-react that uses hooks itself.

Although I am also looking forward to that my intention is to try out hooks in my projects and start using them, even if mobx-react itself can not yet be switched.

This is not possible as observer causes the above error.

Looking at the code (https://github.com/mobxjs/mobx-react/blob/master/src/observer.js#L321-L343) I get the feeling that observer is converting a function component to a class which will not work when using hooks?

So I guess we will have to wait for #588 to be able to use hooks together with mobx.

I have a working prototype now that fixes the error you are seeing (see #588). https://github.com/johot/mobx-react

Closing in favor of #588. We won't be actively supporting a feature that is not actually released.

The simple work around is to use <Observer> sections in your fucntion components, instead of observer wrapper around it

@mweststrate I did not know about <Observer>. Thanks for the tip.

Please give me an example.

@davidtran observer((props) => rendering) is the same as (props) => <Observer>{() => rendering}</Observer>, but the latter has the benefit that it doesn't turn your function component into a class component.

You can now also use observer from mobx-react-lite

Hi guys.

I did your tips but the problem is still yet. May someone help me to fix it?
I'm using the latest version of React and mobx and the class way of mobx for managing stores and when I call an action function, everything looks good and the store will be updated but DOM can't update.

Thank you in advance and I appreciate your help.

@ali-master please open a fresh issue, following the normal format with reproduction and such.

Thank you, I will