前端学习

React Hooks 异步报错

2020-09-14  本文已影响0人  小盐_814e

使用asyncImportComp异步加载路由时报错

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.in](http://function.in/) Notification

我对hooks也不太了解,网上查了下
来源:https://blog.csdn.net/sinat_17775997/article/details/102671301

从网上找了下解决方法

// 省略组件其他内容,只列出 diff
useEffect(() => {
    let isUnmounted = false;
    (async () => {
        const res = await fetch(SOME_API);
        const data = await res.json();
        if (!isUnmounted) {
            setValue(data.value);
            setLoading(false);
        }
    })();
 
    return () => {
        isUnmounted = true;
    }
}, []);

我的代码修改后

// asyncImportComp.js
import React, { useState, useEffect } from 'react'

const asyncImportComponent = function (importComp) {
  function AsyncComponent(props) {
    const [Comp, setComp] = useState(null)
    useEffect(() => {
      let isUnmounted = false;
      const fetchComponent = async() => {
        try {
          const { default: importComponent } = await importComp();
          if (!isUnmounted){
            setComp(() => importComponent)
          }
        } catch (e) {
          throw new Error('加载组件出错')
        }
      }

      fetchComponent();
      return () => {

        isUnmounted = true;
      }
    }, [])
    return (
      Comp ? <Comp {...props} /> : <div>加载中...</div>
    )
  }
  return AsyncComponent
}

export default asyncImportComponent

警告消失

上一篇下一篇

猜你喜欢

热点阅读