我在这种情况下使用的一种常见模式是
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
});
}
}
这将停止已卸载/正在卸载组件上的任何状态设置