Warning: useEffect must not return anything besides a function, which is used for clean-up. You returned: undefined.
ID: react/effect-cleanup-not-a-function
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
Root Cause
The callback passed to useEffect returns a value that is not a function (e.g., undefined, null, an object, or a Promise), which violates the rule that the return value must be a cleanup function or nothing.
generic中文
传递给 useEffect 的回调返回了一个非函数的值(例如 undefined、null、对象或 Promise),违反了返回值必须是清理函数或无返回值的规则。
Official Documentation
https://reactjs.org/docs/hooks-effect.html#effects-with-cleanupWorkarounds
-
95% success If you need async operations, define an async function inside the effect and call it immediately: useEffect(() => { const fetchData = async () => { ... }; fetchData(); }, []);
If you need async operations, define an async function inside the effect and call it immediately: useEffect(() => { const fetchData = async () => { ... }; fetchData(); }, []); -
90% success If you need a cleanup function, return a function explicitly: useEffect(() => { const subscription = source.subscribe(); return () => { subscription.unsubscribe(); }; }, []);
If you need a cleanup function, return a function explicitly: useEffect(() => { const subscription = source.subscribe(); return () => { subscription.unsubscribe(); }; }, []);
中文步骤
If you need async operations, define an async function inside the effect and call it immediately: useEffect(() => { const fetchData = async () => { ... }; fetchData(); }, []);If you need a cleanup function, return a function explicitly: useEffect(() => { const subscription = source.subscribe(); return () => { subscription.unsubscribe(); }; }, []);
Dead Ends
Common approaches that don't work:
-
Adding an empty return statement (return;)
30% fail
This is actually correct if the function returns nothing, but if the problem is an async function, adding return; doesn't fix the implicit Promise return.
-
Wrapping the async code in a separate function and calling it
40% fail
If the async function is still used as the effect callback, it still returns a Promise. The fix is to define async inside the effect, not as the effect itself.
-
Using useEffect(async () => { ... }, [])
70% fail
An async function always returns a Promise, which is not a valid cleanup function. React will fire this warning and the cleanup may not work.