【问题标题】:How to cancel promise in componentWillUnmount() without using this.isMounted?如何在不使用 this.isMounted 的情况下取消 componentWillUnmount() 中的承诺?
【发布时间】:2019-01-27 17:02:19
【问题描述】:

当用户停止输入时我必须调用 API 并且它工作得非常好。当按下回车键时我必须安装。 我做了一个Mock Component here 来做这个。

但是,当组件被卸载时,它会显示错误Cannot call setState on an unmounted component。以前我用this.isMounted 处理了这个错误。现在,我尝试使用 React Blog 中提到的 componentWillUnmount 中的承诺取消来处理它。

this.cancellablePromise = makeCancelable(getSearchResults(word));

      this.cancellablePromise.promise
        .then(res => {
          console.log({ res });
          this.setState({ values: res });
        })
        .catch(err => console.log("error", err));
      console.log("in data ", this.cancellablePromise);
    }

cancellablePromise 在 promise 得到解决后被分配。所以在 componentWillUnMount 中有一个 null 对象用于cancellablePromise 实例。

【问题讨论】:

  • makeCancelable 到底是做什么的?
  • 你应该看看像github.com/slorber/awesome-debounce-promise这样的基于promise的去抖动。正如这里所解释的,可观察对象更适合此类任务,stackoverflow.com/a/54328220/3731501。使用 RxJS debounce 很容易。
  • 如果我们跟踪所有承诺并取消它,它就会起作用......
  • @estus 谢谢你,我会看看它
  • 现在工作正常

标签: reactjs promise


【解决方案1】:

看起来你只需要做以下事情:

myAwesomeMethod = () => {
    this.cancellablePromise = makeCancelable(getSearchResults(word));
    this.cancellablePromise
        .then(...)
        .catch(...)
}

componentWillUnmount() {
    this.cancellablePromise && this.cancellablePromise.cancel();
}

this.cancellablePromise 仅在您在使用 promise 调用方法调用之前卸载组件的情况下才会未定义。

【讨论】:

    【解决方案2】:

    问题是您的handleChange 方法调用debouncedGetSearchResult,但您在getSearchResult 中初始化this.cancellablePromise。这会在您初始化 this.cancellablePromise 之前留下一个 500 毫秒的卸载窗口。

    您需要重新进行此操作,以使去抖动成为可取消承诺的一部分,而不是在它之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2018-09-27
      • 2015-10-11
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      相关资源
      最近更新 更多