解决React 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, ... useEffect cleanup function.

在写react程序时遇到警告:

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 a useEffect cleanup function.

我们看到,react说无法对卸载的组件执行React状态更新,我造成了内存泄漏,并且报错最后一句说让我在useEffect的清理函数中取消所有异步任务。

但是实际上我都代码中没有使用useEffect,这该如何取消异步任务?

实际上我的代码里存在一处条件渲染,并且在其中使用了onChange对Select组件的值做了监听,当条件为false是会卸载该组件,然而onChange还在监听并在回调中去set状态,这就是原因了。

于是我将条件渲染改为:

style={{ display: isSelecting(index, idx) ? 'block' : 'none' }}
return (
    <div className="wrap">
        <div className="cell"
            style={{ display: isSelecting(index, idx) ? 'block' : 'none' }}
        >
            <Select size="small" className='width'
                defaultValue={CurrPropType}
                onChange={onChangePropType}
                options={PropTypes}
            />
        </div>
        <div className="cell"
            style={{display: !isSelecting(index, idx) ? 'block' : 'none'}}
            onClick={() => updateSelected(index, idx, true, type)}
        >
            <PropTypeName type={type} />
        </div>                                                                        
    </div>
)

问题解决。

此外,useEffect中有异步任务的就很好解决了,在useEffect最后return一个清理函数,清理调相关内容就行了。

posted @   野生猿rang  阅读(258)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示