相关疑难解决方法(0)

无法在已卸载的组件上执行React状态更新

问题

我正在React中编写一个应用程序,无法避免出现一个超级常见的陷阱,该陷阱正在调用setState(...)after componentWillUnmount(...)

我非常仔细地查看了我的代码,并尝试放置一些保护子句,但是问题仍然存在,并且我仍在观察警告。

因此,我有两个问题:

  1. 我如何从堆栈跟踪中找出哪个特定的组件和事件处理程序或生命周期挂钩负责违反规则?
  2. 好吧,如何解决问题本身,因为我的代码在编写时就考虑到了这种陷阱,并且已经在试图防止这种情况发生,但是某些底层组件仍在生成警告。

浏览器控制台

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 TextLayerInternal (created by Context.Consumer)
    in TextLayer (created by PageInternal) index.js:1446
d/console[e]
index.js:1446
warningWithoutStack
react-dom.development.js:520
warnAboutUpdateOnUnmounted
react-dom.development.js:18238
scheduleWork
react-dom.development.js:19684
enqueueSetState
react-dom.development.js:12936
./node_modules/react/cjs/react.development.js/Component.prototype.setState
react.development.js:356
_callee$
TextLayer.js:97
tryCatch
runtime.js:63
invoke
runtime.js:282
defineIteratorMethods/</prototype[method]
runtime.js:116
asyncGeneratorStep …
Run Code Online (Sandbox Code Playgroud)

javascript setstate typescript lodash reactjs

28
推荐指数
11
解决办法
3万
查看次数

反应钩。无法在已卸载的组件上执行React状态更新

我收到此错误:

无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,请取消使用useEffect清理功能中的所有订阅和异步任务。

当开始获取数据并卸载组件时,但是函数试图更新已卸载组件的状态。

解决此问题的最佳方法是什么?

CodePen示例

default function Test() {
    const [notSeenAmount, setNotSeenAmount] = useState(false)

    useEffect(() => {
        let timer = setInterval(updateNotSeenAmount, 2000) 

        return () => clearInterval(timer)
    }, [])

    async function updateNotSeenAmount() {
        let data // here i fetch data

        setNotSeenAmount(data) // here is problem. If component was unmounted, i get error.
    }

    async function anotherFunction() {
       updateNotSeenAmount() //it can trigger update too
    }

    return <button onClick={updateNotSeenAmount}>Push me</button> //update can be triggered manually
}
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

8
推荐指数
3
解决办法
3189
查看次数

标签 统计

reactjs ×2

javascript ×1

lodash ×1

react-hooks ×1

setstate ×1

typescript ×1