学无先后,达者为师

网站首页 编程语言 正文

React警告:Can‘t perform a React state update on an unmounted component.解决

作者:A plain girl 更新时间: 2022-07-22 编程语言

React警告:Can’t perform a React state update on an unmounted component.解决

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.
    in Banner

在这里插入图片描述

原因分析:

React在生命周期中设置了没有清除的定时器,或者没有操作了state,可能会造成数据的内存泄露问题,所以会有警告存在

例如:

   componentDidMount(){
	this.state.timer = setTimeout(()=>{
			this.next()
		},2000);
	}

解决方案:

在React的最后一个生命周期中,将函数return或者将定时器清除等。

例如:

componentWillUnmount(){
	clearTimeout(this.state.timer)
}

原文链接:https://blog.csdn.net/qq_43932341/article/details/125686790

栏目分类
最近更新