有什么方法可以取消 mobx-state-tree 中以前的异步操作(类似于 redux-saga 中的 takeLatest)

Is there any way to cancel previous async action in mobx-state-tree (Similar to takeLatest in redux-saga)

目前,我正在使用 MST 作为状态管理库开发我的 react-native 应用程序。

现在我遇到了一个问题,应用程序有机会触发 2 个类似的 API 调用。 第一个 API 在第二个之后响应,导致数据被过时的响应覆盖。

在 redux-saga 中,我们可以使用 takeLatest 来确保我们从最新的请求中获取数据。我正在 MST 中寻找类似的功能来解决这个问题。

我发现 Axios 的取消令牌可以取消 API 调用,但我想看看有没有更通用的异步方式来解决它。

据我所知,在 MobX 或 MST 中没有内置功能,因此您需要自己实现它。

我通常用来取消承诺的通用方法是这个(归功于https://wanago.io):

class RaceConditionGuard {
  private lastPromise: PromiseLike<unknown> | null = null;

  getGuardedPromise<T>(promise: PromiseLike<T>) {
    this.lastPromise = promise;
    return this.lastPromise.then(this.preventRaceCondition()) as Promise<T>;
  }

  preventRaceCondition() {
    const currentPromise = this.lastPromise;
    return (response: unknown) => {
      if (this.lastPromise !== currentPromise) {
        return new Promise(() => null);
      }
      return response;
    };
  }

  cancel = () => {
    this.lastPromise = null;
  };
}

以及用法,假设您有一些基于 class 的商店,例如:

class SomeStore {
  raceConditionGuard = new RaceConditionGuard();

  loadItems = () => {
    // Previous call will be automatically canceled (it will never resolve actually)
    this.raceConditionGuard
      // Wrap your async operation
      .getGuardedPromise(fetchSomething())
      // Handle result somehow
      .then(this.handleResult);
  };

  // Or you can cancel manually
  cancelLoading = () => {
    this.raceConditionGuard.cancel()
  }

  // ...
}