codestates / codestates/Almost-There

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

Open
#131 0 comments 0 reactions 1 assignee Claimed by @JHL71 View on GitHub
Complete
Dominant language
TypeScript
Stars
0
Forks
0
PR merge metrics
No merged PRs in 30d

Description

> 해결된 에러라면 라벨에 'Complete' 를 달아주세요.
> 미해결된 에러라면 라벨을 'In progress' 로 변경해주세요.

### 어떤 에러인가요?
- setTimeout 함수를 써서 시간을 업데이트 하다가 페이지를 이동했을 때 setTimeout으로 비동기적으로 실행된 함수가 이미 사라진 컴포넌트의 state를 업데이트하는 에러

### 에러 메시지

```
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에서 return 으로 함수를 넘겨주면 컴포넌트가 unmount 될 때 그 함수가 실행된다. setTimeout이 리턴하는 timeout id를 변수에 저장하고 useEffect의 return 값으로 clearTimeout(id)를 실행하는 함수를 넘겨줬다.

```js
useEffect(() => {
let id: any;
if (boo) {
id = setTimeout(minusOne, 1000);
}
return () => {clearTimeout(id)}
}, [seconds]);
```

### 에러 핸들링을 위해 참고한 레퍼런스 링크

[React - Using the Effect Hook](https://ko.reactjs.org/docs/hooks-effect.html)
[MDN - clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.