您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

在这种情况下使用的一种常见模式是

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

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

其他 2022/1/1 18:15:34 有567人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶