[react] 常見錯誤訊息一覽 Error Messages
components 在使用 props 時忘了帶大括號
錯誤訊息
Uncaught Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
可能原因
- component 在使用 props 時參數忘了帶大括號:
// TodoItem 這個 function 的參數忘了帶大括號
const TodoItem = (text, onClick) => {
return <li onClick={onClick}>{text}</li>;
};
Can't perform a React state update on an unmounted component
錯誤訊息
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.
錯誤來源:ReactFiberWorkLoop @ github/facebook
可能原因
- 在 React Component 已經 unmount 之後還去呼叫了該 component 的
setState()
方法。 - 這在非同步的情況中一不小心很常出現,例如說原本打算拉完資料才去
setState()
,但等拉到該資料後,該 component 已經 unmount 了。
解決辦法
參考 React Snippets 中 isUnmounted
的使用。
參考
- Prevent React setState on unmounted Component @ ROBIN WIERUCH
- isMounted @ Github
- React-hooks. Can't perform a React state update on an unmounted component @ StackOverflow