微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 setInterval 并清除间隔时,无法对卸载的组件警告执行 React 状态更新为什么?

如何解决使用 setInterval 并清除间隔时,无法对卸载的组件警告执行 React 状态更新为什么?

我正在测试一个组件,该组件使用钩子每 30 秒更新一次值。它通过每三十秒调用 setInterval 来实现。我正在清除钩子的 useEffect 钩子中的这个间隔。当我在 Jest 中运行测试时,我得到 Warning: Can't perform a React state update on an unmounted component。我正在清除 useEffect 钩子的清理函数中的间隔,但这仍然不能解决问题。

如果我在清理函数中将 isCanceled 布尔值设置为 true,并在调用 setter 之前检查该值的真实性,我将不再遇到此问题。我的问题是:我不太明白为什么会这样。我知道在组件卸载之后和 clearInterval调用之前 setInterval内容运行之前一定有一个间隙,但我没有看到它。谁能解释一下?预先感谢您的帮助。

const useCalculatedMinutes = (time: EpochTime): string => {
    let isCanceled = false;
    const [mins,setMins] = useState(getMinutesFromNow(time));
    const THIRTY_SECONDS = 30000;

    const updateMinutesRegularly = () => {
        return setInterval(() => {
            // if (!isCanceled) { // This check will prevent the warning from happening.
                setMins(getMinutesFromNow(time));
            // }
        },THIRTY_SECONDS);
    };

    useEffect(() => {
        const interval = updateMinutesRegularly();
        return () => {
            // isCanceled = true; // Doing this to indicate the component is Now unmounted; this works.
            clearInterval(interval);
        };
    },[mins]);

    return mins;
};

编辑:我也在使用 Jest 的 runOnlyPendingTimers 函数。测试如下:

it('increments the time after one minute',async () => {
    const ONE_MINUTE_FROM_Now = Date.Now() + 60100 * 1;
    renderDashboardScreen();
    await waitForElementToBeRemoved(screen.getByText(/Loading.../));
    expect(screen.getByText(/10 mins/)).toBeInTheDocument();
    await waitFor(() => {
      jest
       .spyOn(global.Date,'Now')
       .mockImplementation(() => ONE_MINUTE_FROM_Now);
        jest.runOnlyPendingTimers(60000);
      });
        expect(await screen.findByText(/11 mins/)).toBeInTheDocument();
    });

Additionally,I have other tests in the file. If I comment out all of the others,I don't get the warning. If I uncomment any of the other tests,I get the warning again.  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?