![](/img/trans.png)
[英]Cleaning up Lodash debounce function in React useEffect hook
[英]Cleaning up axios useEffect function
我的 useEffect 不断收到此错误。
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 的警告?
export default function GetDemo()
{
const ListLoading = LoadingComponent(Demo);
const [appState, setAppState] = useState({
loading: true,
posts: null,
});
useEffect(() =>
{
axiosInstance.get('demo/all/').then((res) =>
{
const allPosts = res.data;
setAppState({ loading: false, posts: allPosts });
});
}, []);
return (
<ListLoading isLoading={appState.loading} buckets={appState.posts} />
);
};
我不确定要在 useEffect 依赖数组中添加什么,我尝试使用setAppState
和 state 本身,但仍然收到此警告。
在调用setAppState
之前检查组件是否仍然挂载:
useEffect(() => {
let mounted = true;
axiosInstance.get('demo/all/').then((res) => {
const allPosts = res.data;
if (mounted) {
setAppState({ loading: false, posts: allPosts });
}
});
return () => {
mounted = false;
};
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.