在react中,前端通常需要向服务器发起异步请求,而在使用react的时候,如果这个组件最初加载的时候就发起这个异步请求,然后在返回结果中进行setState({}),这时候有可能会遇到这个警告:
问题内容:Warning: setState(...): Can only update a mounted or mounting component
问题分析:通常是因为组件并没有装载上便开始执行setState({}),这是需要这样处理:在组件中写入:
haveChange = () => {
this.props.info(this.props.ID, this.props.path).then((response) => {
if(this.mounted){
// code
}
})
}
// make sure that setState after component mount (otherwise error)
componentWillMount(){
this.mounted = true;
}
componentWillUnmount() {
this.mounted = false;
}
componentDidMount() {
this.haveChange();
}
这样就可以避免报错信息了