mobxjs / mobx-react-devtools

[DEPRECATED] Tools to perform runtime analyses of React applications powered by MobX and React
MIT License
1.23k stars 49 forks source link

Mobx-react-devtools reports `ReferenceError: window is not defined` #101

Closed timnew closed 6 years ago

timnew commented 6 years ago

Mobx-react-devtools reports ReferenceError: window is not defined when render the site in Next.js

I tried to wrapped the render code with different guards, but it doesn't help:

// This doesn't help
renderDevTools() {
    return  process.browser ? (<DevTools />) : null
}
// This doesn't help
renderDevTools() {
    if (typeof window !== 'undefined') {
      return <DevTools />
    }
 }

In the end, I found the error was yield when import the type rather than render it. By de-uglify the index.js I found the issue occurs on iife call, which is executed when the code is required.

!(function(e, t) {
  'object' == typeof exports && 'object' == typeof module
    ? (module.exports = t(require('react'), require('mobx-react'), require('mobx')))
    : 'function' == typeof define && define.amd
      ? define(['react', 'mobx-react', 'mobx'], t)
      : 'object' == typeof exports
        ? (exports.mobxDevtools = t(require('react'), require('mobx-react'), require('mobx')))
        : (e.mobxDevtools = t(e.React, e.mobxReact, e.mobx))
})(window, function(e, t, n) { // <--------- This is the problem
  return (function(e) {
...

Not sure how to fix this on the client side, as import is executed out of the normal logic flow.

Now I worked around it by fork the code and changing window in iife to (typeof window === 'undefined' ? global : window), looks patched the issue.

timnew commented 6 years ago

I guess the issue is caused by next.js's server-side rendering, that the code is executed in node environment rather than browser one.

mweststrate commented 6 years ago

Seems to be caused by https://github.com/webpack/webpack/issues/6522, will use one of the work arounds