如何解决有没有办法取消 mobx-state-tree 中的先前异步操作类似于 redux-saga 中的 takeLatest
目前,我正在使用 MST 作为状态管理库来开发我的 react-native 应用程序。
现在我遇到了一个问题,应用程序有机会触发 2 个类似的 API 调用。 第一个 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 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()
}
// ...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。