【问题标题】:Argument of type '() => () => Promise<void>' is not assignable to parameter of type 'EffectCallback''() => () => Promise<void>' 类型的参数不可分配给 'EffectCallback' 类型的参数
【发布时间】:2021-08-05 09:00:52
【问题描述】:

我的代码是:

    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);
                }
            }
        };
    }, []);

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

【问题讨论】:

  • 一个效果回调应该返回 void,你的返回一个 promise 的 void。

标签: reactjs typescript next.js


【解决方案1】:

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

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

或者

它应该返回一个() =&gt; void类型的“cleanup”函数,例如:

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

您收到错误是因为代码中的清理函数不是() =&gt; void 类型,而是() =&gt; Promise&lt;void&gt; 类型,例如:

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

useEffect(() => {
  console.log("Hi")
  return async () => { // WRONG
    console.log("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
};

【讨论】:

    【解决方案2】:

    useEffect 回调的返回类型应为 void。所以你不能返回一个 Promise:

    useEffect(() => {
            document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)';
            window.$crisp.push(['do', 'chat:hide']);
    
            window.$crisp.push(['do', 'chat:show']);
            document.querySelector('body').style['background-color'] = '#ffffff';
            if (router.query.id) {
                firebase.firestore()
                    .doc(`documents/${router.query.id}`)
                    .get()
                    .then((resDoc) => {
                        if (resDoc.exists) {
                            clearDocPrediction(router.query.id);
                        }
                    });
            }
    }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多