解决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 @ 2024-07-17 16:09  我的五年  阅读(470)  评论(0)    收藏  举报