无法在卸载的组件上调用setState(或forceUpdate)

Nik*_*ola 22 javascript reactjs react-lifecycle

我试图在组件更新后从服务器获取数据,但我无法做到这一点.据我所知componentWillUnmount,当组件即将被销毁时被调用,但我永远不需要销毁它因此对我来说没用.这会是什么解决方案?什么时候我应该设置状态?

async componentDidUpdate(prevProps, prevState) {
  if (this.props.subject.length && prevProps.subject !== this.props.subject) {
    let result = await this.getGrades({
      student: this.props.id,
      subject: this.props.subject
    });
    this.setState({
      subject: this.props.subject,
      grades: result
    });
  }
}

async getGrades(params) {
  let response, body;

  if (params['subject'].length) {
    response = await fetch(apiRequestString.gradesBySubject(params));
    body = await response.json();
  } else {
    response = await fetch(apiRequestString.grades(params));
    body = await response.json();
  }

  if (response.status !== 200) throw Error(body.message);

  return body;
}
Run Code Online (Sandbox Code Playgroud)

完整错误:

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, 
but it indicates a memory leak in your application. To fix, cancel all subscriptions and
asynchronous tasks in the componentWillUnmount method.
Run Code Online (Sandbox Code Playgroud)

Ste*_*han 46

我在这个例子中使用的一个常见模式是类似的

componentWillUnmount() {
    this.isCancelled = true;
}
Run Code Online (Sandbox Code Playgroud)

然后在您正在等待解析异步函数的代码中,您将在设置状态之前添加一个检查:

async componentDidUpdate(prevProps, prevState) {
    if (this.props.subject.length && prevProps.subject !== this.props.subject) {
        let result = await this.getGrades({
            student: this.props.id,
            subject: this.props.subject
        });
        !this.isCancelled && this.setState({
            subject: this.props.subject,
            grades: result
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

这将停止对已卸载/卸载组件的任何状态设置