❗️Error/오류를 해결하자!

Can't perform a React state update on a component that hasn't mounted yet. 에러 해결하기

hellohailie 2022. 8. 18. 17:54

 

✔️ 에러 코드

Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead.

해석해보기~~

아직 마운트되지 않은 구성 요소에서 React 상태 업데이트를 수행할 수 없습니다. 이는 비동기식으로 나중에 호출이 구성 요소를 업데이트하려고 시도하는 렌더링 함수에 부작용이 있음을 나타냅니다. 대신 이 작업을 useEffect로 이동합니다.

 

 

✔️ 에러가 나온 이유

fake-server에서 데이터를 가지고 오는데 문제가 생겼다. 

아마 useEffect 없이 바로 fetch를 사용해서 렌더링에 side effect가 발생할 수 있다는 것을 알려주는 에러이다. 

 

마지막 줄에 "Move this work to useEffect instead." 라고 아주 친절하게 알려줘서 바로 에러를 해결했다!

 

리액트는 참 친절하구나! 👏

 

👇에러코드 👇

import { useState } from "react";
import styled from "styled-components";

const Section = styled.div`
  border: 1px solid black;
  margin: 5px;
  padding: 5px;
  display: flex;
  justify-content: space-between;
`;

const BucketListMain = () => {
  const [data, setData] = useState("");

  fetch("http://localhost:3001/data/")
    .then((response) => response.json())
    .then((data) => setData(data));
  return (
    <Section>
      {data}
      {/* <p>{data.id}</p>
      <p>{data.city}</p>
      <p>{data.doing}</p>
      <img>{data.photo}</img> */}
    </Section>
  );
};
export default BucketListMain;

👇에러  수정 코드 👇

useEffect(() => {
    fetch("http://localhost:3001/data/")
      .then((response) => response.json())
      .then((item) => setData(item))
      .catch((err) => {
        alert(err);
      });
  }, ["http://localhost:3001/data/"]);

 

참고)

https://bobbyhadz.com/blog/react-cant-perform-react-state-update-on-unmounted-component

 

Can't perform a react state update on an unmounted component | bobbyhadz

To solve the Warning: Can't perform a React state update on an unmounted component, declare an `isMounted` boolean in your `useEffect` hook that is used to track whether the component is mounted. A component's state should only be updated if the component

bobbyhadz.com

 

 

😃 잘못된 개념 전달이 있다면 댓글 부탁드립니다. 저의 성장에 큰 도움이 됩니다🤓