javascript - 无法对已卸载的组件调用 setState(或forceUpdate)

标签 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;
}

完整错误:

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.

最佳答案

我在本例中使用的常见模式类似于

componentWillUnmount() {
    this.isCancelled = true;
}

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

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
        });
    }
}

这将停止未安装/卸载组件上的任何状态设置

关于javascript - 无法对已卸载的组件调用 setState(或forceUpdate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428842/

相关文章:

javascript - 通过多个 php 文件通过 javascript POST 数据

reactjs - 使用 useHistory、useLocation Hook 的 Hook 调用无效

javascript - 在 React 中设置超时

javascript - 未捕获的范围错误 : Maximum call stack size exceeded - ReactJS

reactjs - 为什么我的 React 组件总是被安装、卸载并再次安装?

javascript - 选择单选按钮时如何隐藏日期选择器?

javascript - $.event.handle.apply 在 jQuery 代码中意味着什么?

javascript - 如何获取 Firebase 实时数据库触发器云函数中先前节点和写入/更新节点之间的差异

javascript - React 获取数据然后作为 props 传递?

javascript - React - 使用 componentDidUpdate 根据从另一个函数传递的数据更新状态