react 使用 error 报错
作者:互联网
在使用react 中报错原因总结
01
// Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application.Instead, assign to `this.state` directly or define a `state = {};class property with the desired state in the Router2 component
// 原因是在 constructor 中 调用了 this.setState()
// 解决办法 可以将 this.setState() 操作放在 componentDidMount 中执行
componentDidMount() {
this.init()
}
init = () => {
this.setState({...})
}
02
// 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. at Router2 (http://localhost:3000/static/js/main.chunk.js:1351:5)
// 原因是 react 在组件挂在之后进行了异步操作,在切换路由时,组件已经被卸载,此时异步操作中 callback 还在执行,因此 setState 没有得到值
// 解决办法
// 在卸载时对所有异步操作进行清除, 或者设置flag 不在进行 this.setState() 操作。
componentWillUnmount() {
this.setState = (state, callback) => {
return;
}
// this.setState = () => false;
// clearTimeout(timer)
// ajax.abort()
//
}
// 在组件已经卸载时return,不去设置state:使用react组件this里面的updater属性上的isMounted方法判断组件是否存在,如果不存在,就return,不再去设置setState
if (this.updater.isMounted(this)) {
this.setState({
dashBoardDate: otherDashBoardDate
})
} else {
return
}
// react Hooks 解决:
useEffect(() => {
let isUnmounted = false
const abortController = new window.AbortController
request.get('xxxxxx').then((resp:any):any => {
if(resp.code == 200 && !isUnmounted){ this.setState({ //.... }) }
}).finally(() => {
})
return () => {
isUnmounted = true
abortController.abort
};
},[]);
标签:return,react,state,报错,error,组件,isUnmounted,setState 来源: https://www.cnblogs.com/yidejiyi/p/15670516.html