首页 > 解决方案 > 使用Effect清理功能,防止未挂载的组件异步更新

问题描述

我是 React Hooks 的新手。当我从 About 部分跳到另一个部分时,会显示此警告。无需等待它完成安装。

index.js:1 警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。在 FadeItems (at AboutSection.jsx:32) in div (由 CardBody 创建) 在 CardBody (在 AboutSection.jsx:29) 在 div (由 Card 创建) 在 Card (在 AboutSection.jsx:22) 在 div (在 AboutSection. jsx:19) 在 AbouSection (at About.jsx:9) in section (at About.jsx:7) in About (由 Context.Consumer 创建)

这是 FadeItems 的代码:

import React, { useState } from "react";
import PropTypes from "prop-types";
import { Fade } from "reactstrap";

const FadeItems = (props) => {

  const [count, setCount] = useState(0);

  // const [mount, setMount] = useState(true);
  // useEffect(() => {
  //   // setTimeout(() => {
  //     // let mounted = true
  //       if (mount) {
  //         mount = false;
  //       }

  //     return function cleanup() {
  //         mounted = false
  //     }
  //     // setCount(0);
  //   // }, 300)
  // }) // prevent the unmounted component to be updated

  const { text } = props;
  return (
    <div style={{ backgroundColor: '#282c34', padding: '30px', borderBottom: "solid 2px #764abc"}}>
      {
        text.map((statement, index) => (
          <Fade
            in={count >= index ? true : false}
            onEnter={() =>
              setTimeout(() => {
                setCount(index + 1);
              }, 2000)
            }
            onExiting={() => setCount(-1)}
            tag="h5"
            className="mt-3"
            key={index + 100}
            style={{ backgroundColor: '#282c34' }}
          >
            {statement}
          </Fade>
        ))
      }
    </div>
  );
};

FadeItems.propTypes ={
  text: PropTypes.string,
}.isRequired;

export default FadeItems;

我有一个计时器设置为在 2 秒后挂载 Fade。由道具 onEnter 调用。装上之后。正如此处的 Reacstrap 文档所建议的那样:

淡化项目文档 Reactstrap

代码的注释部分是尝试使用 useEffect 修复。但我还不知道如何正确使用它。如果要检查存储库:

GitHub 存储库

标签: reactjsasynchronousreact-hookscomponents

解决方案


您需要在清理功能中清除设置的计时器useEffect

 const [mount, setMount] = useState(true);
   useEffect(() => {
      const timerId = setTimeout(() => {
        let mounted = true
         if (mount) {
           mount = false;
         }

      return () => {
         clearTimeout(timerId);
      }
   })

推荐阅读