mobxjs / mobx

Simple, scalable state management.
http://mobx.js.org
MIT License
27.56k stars 1.78k forks source link

Cannot read properties of null (reading 'useSyncExternalStore') when using vite module federation #3959

Closed mgreca closed 5 hours ago

mgreca commented 7 hours ago

Intended outcome: I have two apps working with mobx and vite with react 18. Now I want to use vite module federation to make one a host and the other a remote app. I want to use observer in my components:

export const Button = observer(({store}) => {
  const { clicks, increment } = store;
  return (
    <div>
      <button className='shared-btn' onClick={() => increment()}>Click me: {clicks}</button>
    </div>
  )
})

Actual outcome: This button component gets rendered if I don't use an observer, but as soon as I include an observer, it throws me: __federation_shared_…dom-e806fc46.js:317 Uncaught TypeError: Cannot read properties of null (reading 'useSyncExternalStore')

How to reproduce the issue:

As they are two apps, in two servers, I can't share it in a working codesandbox. But I can share the code, based in this simple React Vite app. This is the code sandbox: https://codesandbox.io/p/sandbox/lfyqc8 The serve command will start a host and a remote server. Remote works as expected in http://localhost:5001/, but as soon as it gets called from the host in http://localhost:5000/ the error message appears.

It sounds like a mobx issue for using the useSyncExternalStore, but I'm not sure if it is also a module federation issue with this hook.

NOTE: I've also submitted a bug to vite module federation in case it is an issue with the hook

mgreca commented 5 hours ago

Alright, I figured it out, in my case I'm using mobx and mobx-react, I just added those packages to the shared packages between the host and the remote app. In my case, the server did not need mobx but I've installed it to solve the issue and added to the federation config in the vite.config the following:

shared: ['react', 'react-dom', 'react-router-dom', 'mobx', 'mobx-react']