【问题标题】:React.js No-op in component?React.js 组件中没有操作?
【发布时间】:2021-07-10 20:39:37
【问题描述】:

我相信无操作来自我的 useEffect 所以,我尝试实施清理。但是,我仍然遇到无操作问题。这是错误:

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

这是我的 useEffect 实现:

React.useEffect(() => {
    let isSubbed = true;
    const fetchFormats = async (subbedStatus) => {
        getEGMFormats(enums.EGM_EXPORT_FORMATS)
            .then((data) => {
                subbedStatus && setResponse(data.data);
            })
            .catch((err) => {
                subbedStatus && setErrorStatusCode(err.response.status);
            })
            .finally(() => {
                subbedStatus && setIsSubmitting(false);
            });
    };
    fetchFormats(isSubbed);
    return () => {
        cancelAxios();
        isSubbed = false;
    };
}, [setErrorStatusCode]);

cancelAxios 函数调用正在被导入,但它的功能如下:

export const cancelAxios = () => source.cancel();

我在这里做错了什么,或者它可能在我的组件中的其他地方?这是组件中唯一的useEffect?

【问题讨论】:

    标签: javascript reactjs memory-leaks use-effect


    【解决方案1】:

    嗯...您应该使用闭包中的标志变量,而不是函数参数...

    React.useEffect(() => {
        let isSubbed = true;
        const fetchFormats = async () => {
            getEGMFormats(enums.EGM_EXPORT_FORMATS)
                .then((data) => {
                    isSubbed&& setResponse(data.data);
                })
                .catch((err) => {
                    isSubbed&& setErrorStatusCode(err.response.status);
                })
                .finally(() => {
                    isSubbed&& setIsSubmitting(false);
                });
        };
        fetchFormats();
        return () => {
            cancelAxios(); // not sure what is this...
            isSubbed = false;
        };
    }, [setErrorStatusCode]);
    

    【讨论】:

    • 不完全是解决方案,但很有帮助,所以谢谢。原来我必须在另一个子组件中实现它并删除 cancelAxios()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多