22 01 토이 프로젝트 회고 - ChoDragon9/posts GitHub Wiki
언마운트된 컴포넌트 후 useState로 상태 변경 시 발생하는 에러
에러 로그
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.
원인
컴포넌트 언마운트된 상태에서 API 응답 영향으로 useState를 변경하면 위와 같은 에러가 발생한다.
해결 방안
useEffect에서 unmounted 상태를 체크하고, unmounted일 때 useState를 변경하지 않도록하면 해결할 수 있다.
const [unmounted, setUnmounted] = useState(false);
const [apiResponse, setApiResponse] = useState(null);
useEffect(() => {
return () => {
setUnmounted(true);
};
}, []);
useEffect(() => {
(async () => {
const response = await axios.get('/path');
if (!unmounted) {
setApiResponse(response);
}
})();
}, []);