index.js:1 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.
위와 같은 에러가 발생함.
언마운트된 컴포넌트에 상태 업데이트를 수행할 수 없으니, 모든 subscription, 비동기 작업을 을 취소하라는 의미임.
const CommentView = ({ postId, showLoginModal }: ICommentViewProps) => {
const [refreshing, setRefreshOngoing] = useState(false);
const refresh = () => {
setRefreshOngoing(true);
return api
.getCommentList(0)
.then((response) => {
console.log(response);
})
.catch((e) => {
})
.finally(() => {
setRefreshOngoing(false);
});
};
useEffect(() => {
refresh();
}, [postId]);
}
위의 CommentView 가 처음 진입시 한번 그려진 후 부모뷰의 상태 업데이트에 따라 바로 다시 그려짐.
이에 따라 api.getCommenetList 가 중간에 취소가 되는데, 해당 뷰는 이미 사라졌기 때문에 위와 같은 에러가 발생하고 있음.
unmount 상태여부를 체크할 수 있는 reference 를 두어 unmounted시에는 상태 업데이트를 하지 않도록함.
const CommentView = ({ postId, showLoginModal }: ICommentViewProps) => {
const unmounted = useRef(false);
const [refreshing, setRefreshOngoing] = useState(false);
const refresh = () => {
setRefreshOngoing(true);
return api
.getCommentList(0)
.then((response) => {
})
.catch((e) => {
})
.finally(() => {
if (!unmounted.current) {
setRefreshOngoing(false);
}
});
};
useEffect(() => {
unmounted.current = false;
refresh();
return () => {
unmounted.current = true;
};
}, [postId]);
}