【问题标题】:Can I get an example of how to cancel a MobX flow?我可以获得一个如何取消 MobX 流的示例吗?
【发布时间】:2019-07-19 15:43:41
【问题描述】:

Mobx 官方文档指出,您可以对流返回的 Promise 调用 cancel。 https://mobx.js.org/best/actions.html 只是没有如何做到这一点的例子。

上下文: 在componentDidMount中调用异步动作,我们需要在componentWillUnmount中取消这个动作。还想 setState 说 ui 可以在 promise 解决后呈现。


      componentDidMount() {
        this._fetchRawEguide = this.props.combinedEguide.fetchRawEguide(null, true)
        .then(() => {
          this._fetchRawEguide = null;
          this.setState({   
            loaded: true
          });
        })
      }
      componentWillUnmount() {
        if (this._fetchRawEguide) {
          this._fetchRawEguide.cancel();
        }
      }

Mobx 动作看起来像这样


 @action
   fetchRawEguide = flow(function*(date, redirectOnError = false) {
     try {
       const res = yield request(...);

当它试图调用它时遇到了 .cancel() 不存在的问题。

我尝试将 when() 与常规 await / async 一起使用,但它似乎不起作用。如果有人有一个 await / async 的例子,那就太好了。

【问题讨论】:

  • 我在想完全和我读到的一样,所以感谢你发布这个问题,然后回答它!

标签: reactjs mobx mobx-react


【解决方案1】:

这似乎有效

this._fetchRawEguide = this.props.combinedEguide.fetchRawEguide(null, true);
    this._fetchRawEguide.then(() => {
      this._fetchRawEguide = null;
      this.setState({   
        loaded: true
      });
    });

我认为将 .then 应用于 flow 返回的承诺可能会强制转换它并删除 .cancel 函数

【讨论】:

  • 但是 flow 应该与使用 await 而不是 then()catch()async 函数一起使用,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多