React组件未卸载时,能否调用setState或forceUpdate?

2026-04-02 12:081阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计281个文字,预计阅读时间需要2分钟。

React组件未卸载时,能否调用setState或forceUpdate?

错误信息提示:无法调用setState(或forceUpdate)在一个未挂载的组件上。

报错信息是:p.p1{margin:0;font:12pxamp;quot;HelveticaNeueamp;quot;;color:rgba(69,69,69,1)}span.s1{font:12pxamp;quot;.PingFangSCamp;quot;}Warning:CantcallsetState(orforceUpdate)onanunmoun

报错信息是:

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.

 

 

 

项目中tab切换,内容封装成来一个子组件,在跳转到别的路由页面,然后再返回该页面点击tab切换的时候报上述错误,找了很久的原因,目前得到的分析应该是,在路由跳转过来的时候子组件还未加载到,此时点击切换tab栏(这里需要setState),就会报上述的错误,解决办法如下:

 

设置变量 let isMounted = false

 

然后在componentDidMount周期设置:

React组件未卸载时,能否调用setState或forceUpdate?

componentDidMount(){isMounted = true;}  在componentWillUnmount周期设置:componentWillUnmount(){ isMounted = false}组件render这里判断isMounted的值:{ isMounted && this.state.activeIndex === 1 && }

 

 

 

 

 

 

 

本文共计281个文字,预计阅读时间需要2分钟。

React组件未卸载时,能否调用setState或forceUpdate?

错误信息提示:无法调用setState(或forceUpdate)在一个未挂载的组件上。

报错信息是:p.p1{margin:0;font:12pxamp;quot;HelveticaNeueamp;quot;;color:rgba(69,69,69,1)}span.s1{font:12pxamp;quot;.PingFangSCamp;quot;}Warning:CantcallsetState(orforceUpdate)onanunmoun

报错信息是:

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.

 

 

 

项目中tab切换,内容封装成来一个子组件,在跳转到别的路由页面,然后再返回该页面点击tab切换的时候报上述错误,找了很久的原因,目前得到的分析应该是,在路由跳转过来的时候子组件还未加载到,此时点击切换tab栏(这里需要setState),就会报上述的错误,解决办法如下:

 

设置变量 let isMounted = false

 

然后在componentDidMount周期设置:

React组件未卸载时,能否调用setState或forceUpdate?

componentDidMount(){isMounted = true;}  在componentWillUnmount周期设置:componentWillUnmount(){ isMounted = false}组件render这里判断isMounted的值:{ isMounted && this.state.activeIndex === 1 && }