Reactjs 遇到的warning
下方报错信息是控制台打印出的警告信息,虽然不会影响功能的执行,但是看到有一片红色的报错,会很碍眼。
Warning: Can't perform a React state update 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.
问题主要是我们在与后端进行数据交互的时候,一般都是采用异步的方式去请求数据。当我们是用reactjs时,如果在componentWillMount或者在componentDidMount中进行请求时,在接口返回后我们使用setState({}),这种场景下就会出现这个上述的警告。
产生的原因是组件还未装载上就开始执行this.setState的操作了,参考官网,主要解决方法如下:
componentDidMount () {
this.mounted = true
this.setState({loading:true})
baseAjax({
url:Uri.GET_DISPLAY_TITLES,
data:{}
}).then((res)=>{
if(this.mounted){
this.setState({
checkedDisplayTitles:res.data.displayTitles,
loading:false
})
}
})
}
componentWillUnmount() {
this.mounted = false
}
这样的话,上述警告就会消除了。