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

我正在尝试在组件更新后从服务器获取数据,但是我无法做到这一点。据我了解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

});

}

}

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

以上是 无法在已卸载的组件上调用setState(或forceUpdate) 的全部内容, 来源链接: utcz.com/qa/413717.html

回到顶部