首页 > 解决方案 > React hook setState、setTimeout 内存泄漏

问题描述

import React, { useState, useEffect, useRef } from 'react';
import styles from './TextAnimation.module.scss';

const TextAnimation = () => {
    const [typedText, setTypedText] = useState([
        "Welcome to Byc",
        "Change your Life"
    ]);
    const [value, setValue] = useState();
    const [inType, setInType] = useState(false);
    
    
    
    let attachClasses = [styles.Blink];
    if(inType) {
        attachClasses.push(styles.Typing)
    }
        
    const typingDelay = 200;
    const erasingDelay = 100;
    const newTextDelay = 5000;
    
    let textArrayIndex = 0;
    let charIndex = 0;
    
    const type = () => {
        if(charIndex < typedText[textArrayIndex].length + 1) {
            setValue(typedText[textArrayIndex].substring(0, charIndex));
            charIndex ++;
            setTime();
        } else {
            setInType(false);
            setTimeout(erase, newTextDelay);
        }
    };
    
    const setTime = () => {
        setTimeout(type, typingDelay);
    };
    
    const erase = () => {
        if(charIndex > 0) {
            setValue(typedText[textArrayIndex].substring(0, charIndex - 1));
            charIndex --;
            setTimeout(erase, erasingDelay);
        } else {
            setInType(false);
            textArrayIndex ++;
            if(textArrayIndex >= typedText.length) {
                textArrayIndex = 0;
            }
            setTimeout(type, newTextDelay - 3100);
        }
    };

    useEffect(() => {
        type();
    }, [])
    
    
    return (
        <div className={styles.TextAnimation}>
            <span className={styles.Text} >{value}</span><span className={attachClasses.join(' ')} >&nbsp;</span>
        </div>
    );
};

export default TextAnimation;

我正在尝试制作文字动画,但我收到了这样的消息......

警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。

我该如何解决?

标签: reactjsmemory-leaksreact-hookssettimeoutuse-effect

解决方案


卸载组件时需要清除超时,否则卸载组件后可能会运行超时。

要做到这一点 :

  • 将每个超时的返回值存储在某个 ref 的列表中(React.useRef例如)
  • 返回一个回调,useEffect用于清除超时clearTimeout(<return value of setTimeout>)

推荐阅读