首页 > 解决方案 > '() => Timeout' 类型的参数不能分配给 'number' 类型的参数

问题描述

我正在尝试使用 React 和 TypeScript 清除超时,componentWillUnmount但出现以下错误:

Argument of type '() => Timeout' is not assignable to parameter of type 'number'.ts(2345)

这是我的代码:

  startPolling = (): ReturnType<typeof setTimeout> => setTimeout(() => this.loadData(), this.getTimeout());

  componentWillUnmount = (): void => {
    clearTimeout(this.startPolling); // error is thrown here
  }

我很困惑如何摆脱这个错误。我的代码有什么问题?TIA。

标签: reactjstypescript

解决方案


错误是说clearTimeout()需要一个数字,但您正在传递一个函数。MDN 文档说该参数是“您要取消的超时的标识符”。setTimeout()返回可在此处使用的 id。您需要保存返回值以供以后调用时使用clearTimeout()


推荐阅读