Improve "Cannot dispatch in the middle of a dispatch" error with information on actions
This error is useful to spot cascading actions, but it can sometimes be difficult to track down the cause.
Adding information on the _pendingPayload as well as the payload that triggered the error could be useful. (@iirvine 's Dispatcher has a nice warning message in this spirit: https://github.com/iirvine/fluent-flux/blob/master/src/Dispatcher.js).
How to display each payload? One idea could be having a _displayAction method that you could override when constructing the Dispatcher? Something like:
constructor(options) {
if (options && options.displayAction) {
this._displayAction = options.displayAction;
}
}
_displayAction(payload) {
return payload.type;
}
dispatch(payload) {
invariant(
!this._isDispatching,
'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch. ' +
`Received action '${this._displayAction(payload)}' while still dispatching action '${this._displayAction(this._pendingPayload)}'. `
);
}
I can try to put together a PR for this, but wanted to jot down some ideas here first see what you think...
The dispatcher was designed to be a more abstract component, capable of many uses beyond Flux, and to keep this in sync with Facebook's production code we need to keep it this way. It knows nothing about the payload.type -- a payload may not have a type, if the dispatcher is not being used in a Flux application. So let's remove the ideas here about the action and the type, and just display the whole new payload in the error.
Thanks for the feedback. That makes a lot of sense. A couple of questions though:
- I assume we need to pass strings to
invariant(), so should weJSON.stringify(payload)? What about potentially big payloads (ex: with large arrays)? - Maybe we can choose to leave the error as-is by default, but if the client passes a
displayPayloadfunction to theDispatcherconstructor, more error information will be displayed?
Re #1, it could be but how big is it really going to be? And at this point you've had something of a critical breakdown anyway so it feels less important that you might be hanging the browser on a long JSON.stringify when your app has effectively already crashed.
Sent from my iPhone
On Nov 9, 2014, at 4:46 PM, Nicolas Hery [email protected] wrote:
Thanks for the feedback. That makes a lot of sense. A couple of questions though:
I assume we need to pass strings to invariant(), so should we JSON.stringify(payload)? What about potentially big payloads (ex: with large arrays)? Maybe we can choose to leave the error as-is by default, but if the client passes a displayPayload function to the Dispatcher constructor, more error information will be displayed? — Reply to this email directly or view it on GitHub.
Thank you for reporting this issue and appreciate your patience. We've notified the core team for an update on this issue. We're looking for a response within the next 30 days or the issue may be closed.