react-rails icon indicating copy to clipboard operation
react-rails copied to clipboard

Server rendering: "document is not defined" on refresh (reconcile transaction problem?)

Open olance opened this issue 11 years ago • 21 comments

I'm facing a strange issue...

I have a Rails app configured to use react-rails and use the prerendering feature. When I first load my home page, it renders well without any errors. I can confirm it is prerendered on the server as the received HTML contains the complete markup.

However, when I refresh the page (simple Cmd+R), I get the following error:

Encountered error "ReferenceError: document is not defined" when prerendering AppRouter with { ... state object ... }

There's no trace of a document call/access in my javascript code.

This is how AppRouter is rendered in my view:

<%= react_component('AppRouter', { initialAppState: @application_state }, { prerender: true }) %>

Killing and restarting the dev server "fixes" the problem until the next refresh is done. Changing some code in the AppRouter component will usually have it working again for the next refresh...

So this does look like a cache issue, but I can't figure out what exactly is going on?

olance avatar Jan 11 '15 19:01 olance

After some (painful) digging into V8 trycatch objects, I found the full trace of the error that is triggered:

ReferenceError: document is not defined
    at getActiveElement (<eval>:16383:12)
    at ReactReconcileTransaction.ReactInputSelection.getSelectionInformation (<eval>:10247:23)
    at ReactReconcileTransaction.Mixin.initializeAll (<eval>:15477:30)
    at ReactReconcileTransaction.Mixin.perform (<eval>:15442:12)
    at ReactUpdatesFlushTransaction.Mixin.perform (<eval>:15443:20)
    at ReactUpdatesFlushTransaction.assign.perform (<eval>:13655:38)
    at Object.<anonymous> (<eval>:13734:21)
    at Object.wrapper [as flushBatchedUpdates] (<eval>:12400:21)
    at ReactDefaultBatchingStrategyTransaction.Mixin.closeAll (<eval>:15516:42)
    at ReactDefaultBatchingStrategyTransaction.Mixin.perform (<eval>:15457:16)

This stack matches what I can find around line 16383 in the full V8 evaluated script:

function getActiveElement() /*?DOMElement*/ {
  try {
    return document.activeElement || document.body;
  } catch (e) {
    return document.body;
  }
}

At the top of this script I've got confirmation React is up do date:

/**
 * React v0.12.2
 */

Here's the componentWillMount function of my component:

componentWillMount: function() {
        var self = this;

        // Dispatch initial state
        appContext.dispatchInitialState(this.state);

        if(canUseDOM)
        {
            Router.run(routes, Router.HistoryLocation, function(Handler) {
                var state = self.state;
                state.routeHandler = Handler;
                self.setState(state);
            });
        }
    },

... where canUseDOM is:

canUseDOM = require('react/lib/ExecutionEnvironment').canUseDOM

So is it some sort of revival of facebook/react#1866 or have I done something really bad?

olance avatar Jan 11 '15 22:01 olance

Can you reduce further? If you remove the whole canUseDOM block does it repro? I'm guess it does (canUseDOM should be false there, especially if you're hitting an error about document). If that's the case then you need to look at what appContext.dispatchInitialState is doing.

It might be a bug in React but we don't have enough info yet.

zpao avatar Jan 13 '15 18:01 zpao

Hey @zpao thanks for the feedback :)

You're right I haven't given much info, I focused on the setState whereas it's indeed never called on the server... So yeah, removing the block keeps the "bug" on. However removing the appContext.dispatchInitialState will indeed fix it.

Here's what's going on with my appContext. It's an instance of a Context class which encapsulates a Dispatcher instance from the Facebook Flux library. Stores are registered with that context object and against the Dispatcher instance using the messageHandler method as a dispatch callback. Here's the full Context class:

Dispatcher = require('flux').Dispatcher
BaseStore = require('./base_store')
ActionTypes = require('../constants/common').ActionTypes

class Context
  constructor: ->
    @_dispatcher = new Dispatcher()
    @dispatch = @_dispatcher.dispatch.bind(@_dispatcher)

    @_stores = {}


  ## Store-related methods
  registerStore: (store) ->
    throw new TypeError('store is not an instance of BaseStore') unless store instanceof BaseStore
    throw new Error('A store with the same name is already registered') if @_stores[store.name]?

    # Register the store locally and its message callback against the dispatcher
    @_stores[store.name] = store
    store.dispatchID = @_dispatcher.register(store.messageHandler.bind(store))

  unregisterStore: (storeOrName) ->
    name = if storeOrName instanceof BaseStore then store.name else storeOrName

    # If a store can be found, unregister it from the dispatcher and remove it from our local list
    store = @_stores[name]
    if store?
      @_dispatcher.unregister(store.dispatchID)
      delete @_stores[name]

  findStore: (storeName) -> @_stores[storeName]


  ## Dispatch the initial state object to all registered stores
  dispatchInitialState: (state) ->
    @dispatch({
      type: ActionTypes.INITIAL_STATE
      data: state
    })



module.exports = Context;

My context is initialized before the instantiation/mounting of the AppRouter component takes place:

// Create new context for the app
var appContext = new Context();

// Register stores on the new context
appContext.registerStore(new PostStore());

So, dispatchInitialState just dispatches my initial app context to all registered stores using Disptacher#dispatch which I guess you know/have access to. My only store at the moment being the PostStore, the end of the execution flow from dispatchInitialState will surely be in PostStore#messageHandler or within Dispatcher's own post-dispatch code. Here's the message handler:

messageHandler: (payload) ->
    switch payload.type

      # App initialization: get the initial list of posts
      when ActionTypes.INITIAL_STATE
        @_posts = _.clone(payload.data.posts) if payload.data.posts?

      else return true

    @emitChange()

    true

I thought _.clone could be a cause but the problem still reproduces when I remove it.

Last thing to note probably is that a Store is a subclass of EventEmitter and that emitChange is:

emitChange: -> @emit(Events.CHANGE)

That's it. I hope that's enough information? ^^ I'm happy to give more if needed!

olance avatar Jan 13 '15 22:01 olance

Oh, "quick" update...

I was just noticing that there's no reference to document anywhere in Dispatcher too, so I figure the "bug" is just a side effect of dispatchInitialState being called.

What's happening if it is? Well, the PostStore gets populated with initial posts to display, hence my PostsList and Post components come in! The Post component is just a static component really, all it does is displaying props.

PostsList however registers to changes events from the PostStore and I tracked the bug down to its origin. Here's the PostsList component:

var PostStore = require('../stores/post_store'),
    Post = require('./post');

function stateFromStores() {
    return {
        posts: PostStore.allPosts()
    };
}

var PostsList = React.createClass({
    getInitialState: function() {
        PostStore = this.props.context.findStore('PostStore');
        return stateFromStores();
    },

    componentWillMount: function() {
        PostStore.addChangeListener(this._onChange);
    },

    componentWillUnmount: function() {
        PostStore.removeChangeListener(this._onChange);
    },

    _onChange: function() {
        // Uncommenting the following line would raise 
        // "ReferenceError: undefinedFunction is not defined"
        // undefinedFunction();
        this.setState(stateFromStores());
        // Commenting back the call above and uncommenting this one,
        // the error is "document is not defined"
        // undefinedFunction();
    },

    render: function() {
        var posts = this.state.posts.map(function(post) {
            return <Post key={post.id} post={post} />;
        });

        return (
            <div className="posts">
                {posts}
            </div>
        );
    }
});

module.exports = PostsList;

So it looks like the call to setState from the _onChange callback is the cause of the problem. There's one thing I don't quite get though... when I leave one of the two undefinedFunction calls in _onChange, the first time my page is loaded, I do not get any error about undefinedFunction being undefined. I guess it makes sense because the initial app's state has been dispatched to the PostStore before the PostsList component was ever mounted, so with my app as it is, the store never changes and never posts any other change event. Meaning _onChange wouldn't be called.

However on the second load of the page, an error will be raised and it will be raised from _onChange. Is there some kind of cache of the React app on the server-side that would keep my objects alive and have _onChange be called on the second time the dispatchInitialState function is called? I'm must say I'm a bit lost here!

olance avatar Jan 13 '15 22:01 olance

I've been digging inside React's code a bit trying to trace/find the problem. I'll shamelessly admit I'm quite lost in there :P

However in ReactUpdates, it seems to me the fix that had been brought for facebook/react#1866 has been lost? Well at least the whole "allUnmounted" check is gone, but maybe that's what the asapEnqueued thing is about? (As you can see I don't get much of what's going on in there :) I figured I wouldn't pollute the main repo issues/PR with this, but could that be the source of the problem?

olance avatar Jan 14 '15 23:01 olance

I fixed a problem with the same error message by removing //=require react and //= require react_ujs in my components.js. Not sure if that will help you in this case.

ConradIrwin avatar Jan 27 '15 07:01 ConradIrwin

Hey, thanks @ConradIrwin :) Actually, I have already removed //= require react but I still have //=require react_ujs (in application.js). I could try removing it, although I do need it to mount my components on the client side... how do you do it?

olance avatar Jan 27 '15 09:01 olance

I have two files, serverside.js is used by react prerendering, and application.js is included on the client and pulls in serverside.js.

# app/assets/javascript/react/application.js
//=require react
//=require react_ujs
//=require ./serverside.js
# app/assets/javascript/react/serverside.js
//=require reflux

//=require_tree ./actions
//=require_tree ./stores
//=require_tree ./components

To configure react to use only the serverside file:

# config/application.rb
 config.react.component_filenames = ['react/serverside.js']

To configure the client to read both files:

# layouts/application.html.erb
<%= javascript_include_tag "react/application.js" %>

ConradIrwin avatar Jan 27 '15 17:01 ConradIrwin

Related to @ConradIrwin's advice, react_ujs refers to document all over the place, if it's attempting to prerender in ExecJS there is no document object and it fails.

Related to #55 , anytime components.js loads javascript that has references to the document object, the prerenderer will fail. It looks like the simple solution is Conrad's: anything react specific that can be prerendered in the components.js file, and anything that refers to the document object in the asset pipeline.

(Though I don't think this is your issue)

jmagoon avatar Jan 28 '15 21:01 jmagoon

Thanks for the details @ConradIrwin :)

I have not tested yet but given my trace/analysis of the problem, I'd say that's not my issue indeed. However I will check and report back for good mesure ^^

olance avatar Jan 29 '15 07:01 olance

@ConradIrwin my setup is already similar to what you've done, so that's definitely not the problem.

@zpao don't my explorations help a bit at identifying the problem?

olance avatar Feb 19 '15 19:02 olance

I found this via Google & had the same issue. This messes up when you try to call setState while rendering on the server. (I found out the hard way with react-resolver that setState cannot run on the server-side!)

Anyway, here was my offending code:

componentWillMount() {
  setInterval(updateTime, 1000);
}

updateTime() {
  this.setState({ time: new Date() });
}

Remember that componentWillMount runs on both server & client. Moving the code to componentDidMount, which only happens on the client solved the problem!

http://facebook.github.io/react/docs/component-specs.html#mounting-componentwillmount

ericclemmons avatar Mar 09 '15 22:03 ericclemmons

@ericclemmons from what I've understood, setState is designed to run on the server, and its failing should be considered a bug. The link you gave implies that, and it is confirmed in facebook/react#1866 in these comments by @petehunt and @spicyj

olance avatar Mar 10 '15 09:03 olance

@zpao for what it's worth, I just found that this bug doesn't reproduce when using Node as an ExternalRuntime for ExecJS instead of therubyracer.

olance avatar May 04 '15 06:05 olance

@olance ..I experience the same error on Node v0.12.0 and React 0.13.2 when I pass a Parent's setState to a Child as a prop, then call it within componentWillMount

mweitzel avatar May 07 '15 16:05 mweitzel

I have the same problem without even trying to pass info between child and parent. Just simply calling setState with some values fetched from outside React within componentWillMount on the server side render triggers it. React 0.13.13 / Node v0.10.35

wied03 avatar Jun 09 '15 17:06 wied03

@ericclemmons comment worked for me, I had the issue and was trying to set the initial state for a store in componentWillMount(), changed to componentDidMount() and it fixed the problem. I was using alt and need to set the initial state in case you don't want to use the AltContainer. Thanks, a scary problem to debug

navela avatar Jun 11 '15 01:06 navela

Well of course it worked @navela, componentDidMount() is not called on the server side :) It didn't really "fix" anything though! ;)

olance avatar Jun 11 '15 19:06 olance

no you are right it didn't really fix anything, but server side when a route comes in via express I seed my stores using alt.bootstrap, so it was only an issue client side where I need to call an action to update the stores again, because I am using react-router for client side routing.

navela avatar Jun 12 '15 04:06 navela

Ok ^^

olance avatar Jun 12 '15 06:06 olance