警告:useEffect 不能返回除函数之外的任何内容,该函数用于清理。你返回了:undefined。
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
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
根因分析
传递给 useEffect 的回调返回了一个非函数的值(例如 undefined、null、对象或 Promise),违反了返回值必须是清理函数或无返回值的规则。
English
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.
官方文档
https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup解决方案
-
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(); }; }, []);
无效尝试
常见但无效的做法:
-
Adding an empty return statement (return;)
30% 失败
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% 失败
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% 失败
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.