【发布时间】:2021-08-26 09:06:23
【问题描述】:
第二次导航到TestPage 时遇到错误。该代码在第一次导航时运行良好,但在第二次导航时出现错误。
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.
我注意到,如果我删除 setinterval 块,错误不会发生。
来自 observable 的数据在 Text 中反映良好,但我无法理解导致此错误的原因。因此我的问题是为什么 setState 在可观察订阅中不起作用?
export const testSubject = new Subject<any>();
setInterval(() => {
testSubject.next({ dest: 'any', msg: [] });
}, 2000);
function TestPage({ route, navigation }) {
const [data, setData] = useState<any[]>([]);
useFocusEffect(
useCallback(() => {
testSubject.subscribe(({ dest, msg }) => {
setData(msg);
});
return () => _cleanup();
}, []),
);
const _cleanup = () => {};
return (
<View>
<Text>{JSON.stringify(data)}</Text>
<Button
onPress={() => {
navigation.navigate('home');
}}
title="back"
/>
</View>
);
}
export default TestPage;
【问题讨论】:
-
组件卸载时是否需要取消订阅
testSubject? (还是关闭流?) -
没有。该主题正在多个组件中使用。我在这里展示的只是一个问题的表示。
标签: reactjs react-native rxjs react-navigation