关于在卸载的组件上调用 setState 的警告 [英] Warning about calling setState on an unmounted component

查看:29
本文介绍了关于在卸载的组件上调用 setState 的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警告:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the _class component.

任何想法可能来自哪里.陷阱或类似的东西?

Any idea where it can come from. Gotchas or things like that ?

我已经查看了代码中的所有 setState 并替换了它们以确保.找不到它来自哪里...

I already looked at all the setState in my code and replaced them to make sure. Can't find where it comes from...

我目前的观察:

  • 仅在我的测试中发生
  • 浏览器没问题
  • 我以为我有更多...但随着更多的测试,我变得很困惑,因为它不符合我认为我理解的模式...

所以!我明白错误是什么,但这次警告是关于 _class 组件 所以我迷路了......我刚刚升级到 react-router v4,它需要一个很多变化,所以很难定位警告的来源.

So ! I understand what the error is but this time the warning is about a _class component so I'm lost... I just upgraded to react-router v4 and it needed a lot of changes so it's hard to localize the source of the warning.

有人遇到过类似的问题吗?

Anyone had had a similar problem before ?

我发现了导致问题的 setState.它在 react-router-server 中.我会研究它,看看我是否可以修复它!

I found the setState that were causing problem. It was in react-router-server. I'll look into it to see if I can fix it !

感谢@zerkms 提出使用调试器查看行号的想法,因为终端中没有任何痕迹.

Thanks @zerkms for the idea to look with a debugger to get the line number since there was no trace in the terminal.

我使用了 v8 实验检查器(https://stackoverflow.com/a/39901169/3687661).效果很好:)

I used the v8 experimental inspector(https://stackoverflow.com/a/39901169/3687661). Works pretty good :)

推荐答案

由于 API 调用等异步活动,这很常见.例如,当您在从服务器接收到数据后尝试设置状态并且接收该状态的相应页面未挂载时,就会发生这种情况.

This is common due to async activities like API calls. For example, this happen when you try to set a state after you receive the data from the server and the corresponding page to receive that state is not mounted.

为避免这种情况,请在设置该组件的状态之前检查该组件是否已安装.使用标志进行检查,在 componentDidMount 中说 this.mounted = true 并将 componentWillUnmount 中的标志更改为 false.跨组件使用 this.mounted 来检查组件是否已安装.这将修复警告.

To avoid this, check if the component is mounted before setting state in that component. Use a flag to check, say this.mounted = true in componentDidMount and change the flag to false in componentWillUnmount. Use this.mounted across the component to check if the component is mounted. This will fix the warning.

希望这会有所帮助!

这篇关于关于在卸载的组件上调用 setState 的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆