问题
So the error I get is:
Uncaught (in promise) Error: Invariant Violation: Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.(…)
I've read through countless of posts regarding this error but I can't seem to figure out why I get it. I get the error at pageload, from thereon it works fine. When I remove the loading action: loading: StudentsActions.studentsLoading
it all works fine.
You can find all the code on the github repo
Thanks in advance !
回答1:
You are getting this error because you perform multiple dispatches at the same time. When the page loads, your NavBar
component and your StudentList
component are both rendered, which invokes componentDidMount
on both, and in your case you initiate a dispatch in both places.
You are using a bad flux pattern by having "presentation" components interact with your dispatcher/stores. The correct approach, as pointed out in the flux documentation, is to have a single, top-level component handle dispatches and pass down state to other components via props. In your case, the App
component is the only one that should be aware of the stores or that can dispatch actions.
This has many advantages, such as making your entire application far easier to use and refactor since most components don't know or care where the data comes from. It will also prevent the error you're getting. The reason flux does not allow multiple dispatches at the same time is because allowing it would lead to situations where it's unclear why your application is in a particular state. There is no longer a single line of logic that can be followed to determine what your application is doing.
回答2:
you can user the "defer" option in the dispatcher. In your case it would be like:
StudentAction.getStudents.defer(options);
来源:https://stackoverflow.com/questions/35353108/cannot-dispatch-in-the-middle-of-a-dispatch