【问题标题】:"Warning: Can't perform a React state update on an unmounted component." [closed]“警告:无法对未安装的组件执行 React 状态更新。” [关闭]
【发布时间】:2021-11-09 22:26:09
【问题描述】:

我正在使用 React Native CLI 和 RealmDB 创建一个应用程序来在本地保存数据。在产品列表屏幕上,useEffect 函数返回错误::

 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.

代码:

  const [didMount, setDidMount] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);

  useEffect(() => {
    setDidMount(true);

    async function loadProducts() {
      const realm = await getRealm();

      try {
        if (!didMount) return;
        const data: Product[] = realm
          .objects('Product')
          .sorted('id', true) as any;

        setProducts(data);
      } catch (err) {
        console.error(err);
      }
    }

    loadProducts();

    return function cleanup() {
      setDidMount(false);
    };
  }, []);

【问题讨论】:

  • 为什么需要loadProducts函数...为什么不直接运行useEffect里面的代码
  • 你在哪里声明setDidMountdidMount
  • 当屏幕加载时我想要更新产品
  • 但是你不需要嵌套函数
  • 我在productssetProducts上面声明了

标签: javascript react-native realm use-effect


【解决方案1】:

来自this post

您不能在清理函数中设置状态,而是应确保不会导致进一步的状态更新。

const [products, setProducts] = useState<Product[]>([]);

useEffect(() => {
  let updateProducts = true;

  getRealm().then((realm) => {
    try {
      const data = realm
          .objects('Product')
          .sorted('id', true) as Product[];

      if (updateProducts) setProducts(data);
    } catch (err) {
      console.error(err);
    }
  });

  return () => {
    updateProducts = false;
  };
}, []);

【讨论】:

  • 返回同样的错误
  • 您是否在某处使用任何其他useState 回调,您确定错误是由该组件引起的吗?
  • 或者更有趣的问题,您是否在某处的其他一些清理函数中使用了任何setState 回调?
  • 只表示使用状态
  • 如果你想检查得更好...github.com/sudo-victor/phd.
猜你喜欢
  • 2021-02-24
  • 2021-03-27
  • 2019-09-11
  • 2021-08-07
  • 2020-06-14
  • 1970-01-01
  • 2021-12-03
  • 2021-08-05
相关资源
最近更新 更多