본문 바로가기
FE Development/React

에러노트 - can't perform a react state update on an unmounted component

by 개발자 데이빗 2022. 2. 9.

문제가 되었던 사항

can't perform a react state update on an unmounted component 라는 warning 발생

  •  

해결과정

이슈 서칭

많은 초보 리액트 개발자들이 실수하고 있는 부분이어서 쉽게 원인을 찾아낼 수 있었다.

말 그대로 unmount된 컴포넌트의 상태를 업데이트 할 수 없고 이는 수행되지 않지만 메모리 누수를 일으킬 수 있다는 내용의 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.

 

기존 코드 예시

아래의 코드 예시와 같이 Input 컴포넌트 debounce 메소드를 사용하는 경우였는데 빠르게 아이디와 비밀번호를 입력한 후 로그인 버튼을 눌렀을 때, 0.5초가 지나기 전에 메인 페이지로 전환되며 해당 Input 컴포넌트들이 먼저 unmount 된 후 setDebounceText 함수를 호출해 발생하는 문제였다.

//...
import _ from 'lodash';

//...

const [debounceText, setDebounceText] = useState('');

const debounce = useCallback(
  _.debounce((_prop: string) => {
      setDebounceText(_prop);
  }, 500),
  [],
);

 

해결 결과 코드 예시

warning의 권고사항대로 useEffect cleanup function을 통해 unmount된 경우 setDebounceText 함수를 실행하지 않음으로써 해결하였다.

// ...
import _ from 'lodash';

// ...


let isMount = true;
const [debounceText, setDebounceText] = useState('');

const debounce = useCallback(
  _.debounce((_prop: string) => {
    if (isMount) {
      setDebounceText(_prop);
    }
  }, 500),
  [isMount],
);

useEffect(() => {
  return () => {
    isMount = false;
  }
}, []);

 

 

댓글