flux icon indicating copy to clipboard operation
flux copied to clipboard

Maybe a bug with the error "Cannot dispatch in the middle of a dispatch."

Open fabiozaffani opened this issue 11 years ago • 13 comments

Hi,

Currently I have the following order of events, which are causing this error to occur:

  1. User click's a button to add a product to a cart (the button calls action creator and send ADD_ITEM event, which will be send throught the dispatcher to te stores);
  2. The cart store get this event and update with the product data sended throught the action;
  3. At the same time an API at the UTIL folder calls an async operation to write that update to the server

For testing purposes i'm simulating an local API, which makes the response be imediately.The idea is that the API will dispatch another event through the action creator once the response from the server arrives, something like ADD_ITEM_SUCCESS or ADD_ITEM_ERROR should be dispatched throught the action creator. Currently that's the precisely moment when the error happens, i'm guessing that's because there are almost no delay between the ADD_iTEM and the response from the server event (SUCCESS or ERROR).

However, if I encapsulate the code in a setTimeout function everything works fine, even if I set the timeOut to be at only 1ms or 0. Which leaves me thinking if that might be a bug in the currently version of the dispatcher?

fabiozaffani avatar Dec 05 '14 06:12 fabiozaffani

The current version of the dispatcher is working correctly and I would expect the error to occur, given how you have described the situation.

The reason why it works with a setTimeout is that this puts the faked API response into a new execution context, which only runs after the current execution context completes. Without the setTimeout, you are in the same execution context, and you are then dispatching while you are already in the middle of a dispatch.

Whether the dispatcher could be improved, however, is another question, and I welcome your ideas on how to do that. We don't want to allow overlapping dispatches, as that would make the entire Flux update cycle much more difficult to manage and to reason about. I do recall at one time a suggestion for creating an action queue. But this would encourage bad code, where a person could enqueue cascading dispatches -- a store would respond to a dispatched action and then directly dispatch a new action, rather than providing code for responding to the original action. We do not want the dispatcher to allow that sort of thing.

fisherwebdev avatar Dec 08 '14 01:12 fisherwebdev

Hi fisher, thanks for your reply.

I have been thinking about the best way to solve this and I ended up with a solution that need to use some sort of queue at the dispatcher. Here's my thoughts:

Sync or Async Action Creators?

Looking at the facebook chat example I saw that the external Api call are made through the WebChatApiUtil, the Action Creator call it when creating a message and, once the return from the server is back, the WebChatApiUtil calls an action.

The other solution that I found is the one used by Yahoo and Fluxxor (and maybe some others) that is to make the Action Creator async. Different from the Facebook Chat example, the Action Creator dispatch an action, call the Util that will sync with the server and then wait for the callback from the function.

They both do basically the same thing but one using events and another using callbacks, since all the flux idea is based on an event system I think that the first scenario is the best one.

The problem (that will happen with both solutions above)

Now both these solutions will end up with the same concurrency problem since we never know when the callback will arrive/the event will be fired and the user might initiate new actions while we are waiting for this answer. As the application grows this becomes even more problematic since we can have many information arriving from the server (keeping data in sync). The root of this problem is from the fact that we have two sources of Actions, the View Component (user) or the Api functions (server).

To avoid this the solution that i'm using so far is the following one:

  1. Only the files in Util folder that sync with the server and the Views (react components) can create actions through the Action Creators (for instance, stores should never call actions);
  2. The action creator "fire and forget" the functions in the Util folder as needed to sync with the server, once the payload is ready the Util will then call the action creator it needs with the correct action and payload (just like shown at facebook chat app example);
  3. Stores only receive data from the dispatcher, action creators send action throught the dispatcher only, the views consume data from the store as the store emit changes and stores subscribe to events in the dispatcher to update itself (basic flux idea);
  4. The main difference actually happen at my AppDispatcher file, I created a queued list (using the async npm module), so when the action creator call's something like handleViewAction(source, action) or handleViewServer(source, action), both these functions will put a new request on the last place in the queued line, so the actions will keep getting fired in the same order they arrived and will all be controlled by the AppDispatcher, so the rest of the App can keep working in a synchronous manner and don't worry about any of that;

Bellow that's how my AppDispatcher file currently looks like:

var AppConstants = require('../constants/AppConstants'),
    Dispatcher = require('flux').Dispatcher,
    async = require('async'),
    assign = require('object-assign'),
    PayloadSources = AppConstants.PayloadSources,
    dispatcher,
    queue,
    AppDispatcher;

dispatcher = new Dispatcher();

queue = async.queue( function (task, callback) {
    var payload = {
        source: PayloadSources[task.source],
        action: task.action
    };
    AppDispatcher.dispatch(payload);
    callback();
}, 1); // only one worker, one event at a time

AppDispatcher = assign(dispatcher, {
    handleServerAction: function (action) {
        queue.push({source : 'SERVER_ACTION', action : action});
    },
    handleViewAction: function (action) {
        queue.push({source: 'VIEW_ACTION', action : action});
    }
});

fabiozaffani avatar Dec 11 '14 16:12 fabiozaffani

Would like to hear @fisherwebdev feedback on the strategy used above. We are running into some of the same issues; emitChange triggers a view to change in a manner that dispatches an action (for example a "DebugLog_Add"-action. I

abergs avatar Dec 19 '14 13:12 abergs

Yes, this is a good solution, and has actually been discussed at FB (which is why I mentioned it above) but it's a little bit dangerous for inexperienced Flux programmers. One could easily call AppDispatcher.assign() from within the stores and get involved with cascading actions, which we want to avoid. If you think you have the discipline on your team to not do that, then I'd say you should go for it. But I'd rather not introduce that here in the Flux repo (nor do I want to get involved in additional dependencies on npm modules). If you can figure out a way to introduce this queue that would not allow cascading actions issued by stores, then I'd definitely be more inclined to accept that solution.

fisherwebdev avatar Dec 21 '14 07:12 fisherwebdev

There is a great concept of Statecharts (or UML State Machines) which has some similarities with Flux. It is kind of stuck in academia world, but is well established technology and tested for decades.

One of the similarities with Flux is the dispatch process. They call it RTC (run to completion):

"In the RTC model, the system processes events in discrete, indivisible RTC steps. New incoming events cannot interrupt the processing of the current event and must be stored (typically in an event queue) until the state machine becomes idle again. These semantics completely avoid any internal concurrency issues within a single state machine. The RTC model also gets around the conceptual problem of processing actions associated with transitions, where the state machine is not in a well-defined state (is between two states) for the duration of the action."

http://en.wikipedia.org/wiki/UML_state_machine#Run-to-completion_execution_model

So it is basically the same as Flux dispatch cycle, with one major difference: nested dispatches are allowed, but they are added to (sync) queue and dispatched only after current dispatch cycle is complete.

The problem with Flux dispatcher right now is that sometimes you really need to fire some action in response to other action (and this is perfectly valid case in Statecharts too).

In some cases these actions are created in async handlers (e.g. web api utils). So it kinda works because it doesn't interfere with current dispatch cycle. But why would you allow async operation from store and disallow sync one?

Only because sync operations may interfere with current dispatch process (when your app is in non-consistent state).

I think RTC approach and sync queue solves this problem and doesn't add as much complexity or external dependencies to code as async queue.

vladar avatar May 21 '15 11:05 vladar

That's actually not the reasoning as to why we disallow the dispatch-within-a-dispatch.

The reason is that we are interested in preventing cascading updates. This is the primary problem that causes complexity in the data layer, leading it to become difficult for engineers to reason about how application state is changing.

The Flux perspective is that a mutation should not cause another mutation. Instead, mutations are passive, merely responding to things happening "outside" of the application -- the user clicks, the server responds, the browser cycles an animation frame, etc.

We've talked about and experimented with creating an action queue in front of the dispatcher, but we've stopped short of going forward with it, as it leads immediately to these cascading updates.

fisherwebdev avatar May 22 '15 17:05 fisherwebdev

@fisherwebdev So how do you cope with cascading updates that should happen within the application? Do you fire subsequent actions from stores in a setTimeout callback which in fact relies on the JavaScript internal event queue?

sompylasar avatar May 23 '15 14:05 sompylasar

@sompylasar I've often found that "cascading" updates can often be handled alternatively like so without need to use setTimeout:

someActionCreator.action = function () {
  dispatcher.dispatch({ actionType: "A"...});
  dispatcher.dispatch({ actionType: "B"...});
  ...
};

There won't be a browser repaint until the thread is free.

However, @fisherwebdev, @zpao I'm not sure if this is a good, bad, or ugly practice? Does FB code do this at all or is it just better to merge sequential dispatches 'A' & 'B' above into a third dispatch 'C' which conglomerates them?

sterpe avatar May 23 '15 16:05 sterpe

@sterpe Those sequential calls to dispatch are happening synchronously. They are separate dispatches, so yes this works fine. However, I've never seen that done at FB, and I'm not sure why anyone would do that. We would simply merge them, as you suggested.

@sompylasar We believe that cascading actions are a sign of a design problem, and we avoid them entirely. When all stores are receiving all actions, it's often trivial to simply respond to the original action and waitFor() anything that needs to happen first.

fisherwebdev avatar May 27 '15 09:05 fisherwebdev

Thanks

Sent from my iPhone

On May 27, 2015, at 2:47 AM, Bill Fisher [email protected] wrote:

@sterpe Those sequential calls to dispatch are happening synchronously. They are separate dispatches, so yes this works fine. However, I've never seen that done at FB, and I'm not sure why anyone would do that. We would simply merge them, as you suggested.

@sompylasar We believe that cascading actions are a sign of a design problem, and we avoid them entirely. When all stores are receiving all actions, it's often trivial to simply respond to the original action and waitFor() anything that needs to happen first.

— Reply to this email directly or view it on GitHub.

sterpe avatar May 27 '15 14:05 sterpe

If anyone is interested I've modified the @fabiozaffani 's dispatcher to work without async and it solved all of our Cannot dispatch in the middle of dispatch problems.

In our case components that had their data loaded in store were displaying components that in their turn threw actions to load their content, so that caused the error. Queue solves it and order remains the same.

Here's the code: Note that it's not implementing 2 methods handleServerAction and handleViewAction but just handleAction. It is using tiny sync-queue dependency. https://github.com/tessel/sync-queue

'use strict';

import Flux from 'flux';
import assign from 'react/lib/Object.assign';
import Queue from 'sync-queue';

let queue = new Queue();

let Dispatcher = assign(new Flux.Dispatcher(), {
  handleAction (action, data) {

    let payload = {};

    payload = assign(
      {
        event: action
      },
      data
    );

    queue.place(() => {

      this.dispatch(payload);
      queue.next();
    }); 
  }
});

export default Dispatcher;

mkrn avatar Jun 25 '15 01:06 mkrn

I have a similar situation to @mkrn's, I have a component that can have anywhere from 4-8 child components that each trigger an action to load their own data. When one of those FETCH_DATA actions gets dispatched at the same time as a previous request's SUCCESS action I get the "Cannot dispatch in the middle of a dispatch." error.

I'm wondering if there's a better way for achieving this, for now I think I will go with @mkrn's solution.

tonyjmnz avatar Dec 11 '15 04:12 tonyjmnz

How about following as a solution? I had to override _stopDispatching but FB can provide a flux hook, something like onDispatchCompletion @fisherwebdev

var Dispatcher = require('flux').Dispatcher,   appDispatcher = new Dispatcher();

appDispatcher.handleAction = function(action) {   this.dispatch({     source: 'VIEW_ACTION',     action: action   }); };

appDispatcher.dispatch = function(dispatchAction) {   if ( this.isDispatching() ) {     this._pendingDispatches = this._pendingDispatches || [];     this._pendingDispatches.push(dispatchAction);   } else {     Dispatcher.prototype.dispatch.call(this, dispatchAction);   } };

appDispatcher._stopDispatching = function() {   var pendingDispatch;   Dispatcher.prototype._stopDispatching.call(this);   if (this._pendingDispatches && this._pendingDispatches.length > 0) {     pendingDispatch = this._pendingDispatches.shift();     Dispatcher.prototype.dispatch.call(this, pendingDispatch);   } };

module.exports = appDispatcher;

hankgalt avatar Apr 28 '16 23:04 hankgalt