类型“() => () => Promise<void>”的参数不可分配给“EffectCallback”类型的参数

Sha*_*oon 8 typescript reactjs next.js

我的代码是:

    useEffect(() => {
        document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)';
        window.$crisp.push(['do', 'chat:hide']);

        return async () => {
            window.$crisp.push(['do', 'chat:show']);
            document.querySelector('body').style['background-color'] = '#ffffff';
            if (router.query.id) {
                const resDoc = await firebase.firestore().doc(`documents/${router.query.id}`).get();
                if (resDoc.exists) {
                    await clearDocPrediction(router.query.id);
                }
            }
        };
    }, []);
Run Code Online (Sandbox Code Playgroud)

现在我返回的原因是因为我相信它在卸载时执行函数清理,所以我需要保留它。这是某种构建错误,我不太确定如何解决。任何帮助将不胜感激。

Aje*_*hah 10

Effect 的回调函数应该返回void,例如:

useEffect(() => { // callback; it returns void
  console.log("Hi")
}, [])
Run Code Online (Sandbox Code Playgroud)

或者

它应该返回类型为“ cleanup ”的函数() => void,例如:

useEffect(() => {
  console.log("Hi")
  return () => { // cleanup function of type : () => void
    console.log("Cleanup")
  }
}, [])
Run Code Online (Sandbox Code Playgroud)

您收到错误是因为代码中的清理函数不是 type () => void,而是 type () => Promise<void>,例如:

“() => () => Promise”类型的参数不可分配给“EffectCallback”类型的参数。类型“() => Promise”不可分配给类型“void |” 析构函数'。

useEffect(() => {
  console.log("Hi")
  return async () => { // WRONG
    console.log("Cleanup")
  }
}, [])
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过以下方式重构“cleanup”函数来修复它:

return () => { // Remove async from here
  const clear = async () => { // Create a new async function: clear
    // write your cleanup code here
  };
  clear() // Call the clear() function
};
Run Code Online (Sandbox Code Playgroud)