一次只有一个 MobX-State-Tree 流处于活动状态

Only one MobX-State-Tree flow active at a time

我有一个 MobX-State-Tree (MST) 存储,其中包含一个 flow 异步获取某些项目的操作。可以从应用程序中的多个位置调用此操作,有时甚至可以同时调用,但我只想一次激活一个 flow

在 MST 中是否有任何方法可以 return 当前活动的 flow 如果有,或者如果没有则创建一个新的?

例子

const Thing = types.model({
  id: types.identifier,
  name: types.string,
});

const ThingStore = types
  .model({
    things: types.array(Thing),
  })
  .actions((self) => ({
    // This action will create a new flow every time it is called.
    fetchThings: flow(function* () {
      const things = yield fetchThings();

      self.things = things;
    }),
  }));

您可以创建一个 volatile state 片段,它保留对调用 flow 时 returned 的承诺的引用。如果 flow 已经激活,我们 return 这个承诺。如果没有,我们创建一个新的 flow 和 return that.

例子

const Thing = types.model({
  id: types.identifier,
  name: types.string,
});

const ThingStore = types
  .model({
    things: types.array(Thing),
  })
  .actions((self) => {
    let fetchThingsPromise = null;
    const fetchThings = flow(function* () {
      try {
        const things = yield fetchThings();

        self.things = things;
      } finally {
        fetchThingsPromise = null;
      }
    });

    return {
      fetchThings: function () {
        if (fetchThingsPromise) return fetchThingsPromise;

        fetchThingsPromise = fetchThings.apply(null, arguments);
        return fetchThingsPromise;
      },
    };
  });