Today I Learn/React

[React / Error] Can't perform a React state update on an unmounted component

단추언니 2022. 2. 10. 10:24
반응형

리액트를 이용하여 모달컴포넌트를 개발하던 중 에러 발생

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의 cleanup function을 이용해라

 

에러코드

import { useEffect, useState } from "react";
import axios from "axios";
import Modal from "../components/event/event_modal";

const Result = () => {
	const [modalOpen, setModalOpen] = useState(false)
}

  const openModal = () => {
    setModalOpen(true);
  };
  
  const test = async() => {
  	try {
    	...
    } catch(e) {
    	console.log(e)
    }
  }
  
  useEffect(() => {
    test();
  }, []);
  
  return (
  	<div onClick={openModal}>...</div>
    <Modal open={modalOpen} />
  )

 

해결방법

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

콘솔창에서 알려준 것 과 같이 useEffect의 cleanup function을 이용하여 해결할 수 있다.

반응형