goatslacker / alt

Isomorphic flux implementation
http://alt.js.org/
3.45k stars 322 forks source link

Are calls to setState really batched? #677

Open jiajiawang opened 8 years ago

jiajiawang commented 8 years ago

The doc says

For convenience, calls to setState are automatically batched as they are in React and only one change event will be emitted once the action finishes dispatching".

But from what I've seen, it doesn't seem to behave like that.

The following is the debug log of one dispatching process of https://github.com/iam4x/isomorphic-flux-boilerplate.

-----start dispatching-----
callbackId ID_1
callbackId ID_2
callbackId ID_3
handleDispatch
doSetState false
result of handleDispatch true
emitChange
callbackId ID_4
callbackId ID_5
callbackId ID_6
doSetState false
emitChange
callbackId ID_7
-----stop dispatching-----

As you can see, doSetState does its work. It won't emitChange if it's still dispatching.

However the result of handleDispatch is always true. Then emitChange is called immediately after while it's still dispatching.

As a result of it, we can't dispatch actions within component lifecycle methods like componentDidUpdate. Otherwise, we'll get error "Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch."