본문 바로가기
💻CODING/react. vue

[react] useEffect 메모리 누수 Can't perform a React state update on an unmounted component...

by 코딩하는 갓디노 2022. 1. 7.

useEffect 메모리 누수 Can't perform a React state update on an unmounted component...

 

useEffect의 잘못된 사용으로
인한 메모리 누수 warning 입니다.

 

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. 

 

useEffect 안에서 비동기로직을 실행할때 위와 같은 warning이지만 빨간색의 오류 메시지가 출현합니다.

 

before

    useEffect(() => {
        if (!adminId) {
            history.push(`/adminlogin`);
        } else {
        const bringAlarmData = () => {
                axios.get(common.SERVER_URL + "/report/alarm")
                    .then(res => {
                        if (res.data) {
                            if (isComponentMounted) {
                                setAlarmData(res.data.alarmList);
                            }
                        }
                    })
                    .catch(err => console.log(err))
            }
            bringAlarmData();
        }
    }, [adminId, history]);

 

Warning 해결 방법

 

오류 메시지에 나온 것과 같이 cleanup 함수를 통해 코드를 추가하여 오류를 해결하였습니다.

    useEffect(() => {
        let isComponentMounted = true //1. 추가
        if (!adminId) {
            history.push(`/adminlogin`);
        } else {
            const bringAlarmData = () => {
                axios.get(common.SERVER_URL + "/report/alarm")
                    .then(res => {
                        if (res.data) {
                            if (isComponentMounted) { //2. 추가
                                setAlarmData(res.data.alarmList);
                            }
                        }
                    })
                    .catch(err => console.log(err))
            }
            bringAlarmData();
            return () => { //3. 추가
                isComponentMounted = false
            }
        }
    }, [adminId, history]);

 

참고 링크는 아래로 이동해주세요.

https://juliangaramendy.dev/blog/use-promise-subscription

 

Cancelling a Promise with React.useEffect - Julian​Garamendy​.dev

How to properly subscribe and, more importantly, unsubscribe from a Promise with React.useEffect

juliangaramendy.dev

반응형

댓글