如何修复无法在卸载时执行反应状态更新的问题,即使使用效果已清除



我的项目有问题,我是新来的本地反应者,问题是我收到了这个警告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.

所以我尝试了清理功能,所以我所有的useEffect看起来都像这个

useEffect(()=>{
let mounted = true
if (mounted) {
store.subscribe(()=>{
SetPlaylistData(store.getState().reducer.playlist)
})
}
return () => {
mounted = false;
};
})

我也在使用看起来像的useFocusEffect

useFocusEffect(
useCallback(() => {
let mounted = true
console.log("user info", store.getState().reducer.userInfo);
if (mounted) {
fetchPlaylist(store.getState().reducer.userInfo)
}
return () => {
mounted = false;
};
}, [])
);

所以我担心的是,有没有什么方法可以让这个警告不是由useEffect产生的?

这是React在执行状态更新语句时发出的常见警告,在从视图层次结构中卸载组件时发出的警告。

查看下面的演示

import React, { useRef, useState, useEffect } from 'react';
import { View, Text } from 'react-native'
const Demo = props => {
// ** States
const [isLoading, setLoading] = useState(false)
// ** Refs
const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true // mounted
return () => {
mountedRef.current = false // unmounted
}
}, []);
useEffect(() => {
mountedRef.current && setLoading(true) // update state after verifying the screen mounted status
}, [])
// Any other functions or listeners
const btnPressHandler = () => {
mountedRef.current && setLoading(true) // update state after verifying the screen mounted status
}

return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Demo for handle warning of cannot update state on an unmounted component</Text>
</View>
);
}
export default Demo

最新更新