【问题标题】:Error: Can't perform a React state update on an unmounted component错误:无法对未安装的组件执行 React 状态更新
【发布时间】:2020-08-04 05:53:24
【问题描述】:

我需要你的帮助。 我有一个从 REST 检索数据的组件,当响应返回时,我启用 PDF 的按钮。

const [pdf, setPDF] = useState(false);
const [utente, setUtente] = useState(null);

useEffect(() => {
    const url = ""
    axios.get(url, {
        params: {
            id: props.id
        }
    })
        .then((response) => {
            setPDF(true);
            setUtente(response);
        })
        .catch((err) => {
            setPDF(false);
            setUtente(null);
        });
    return () => {

    };
}, [props.id]);

return (
    <div className="container">
        {
        loadPDF
        ?
        <PDFDownloadLink document={<ComponentPDF utente={utente} />} fileName="utente.pdf">
            { <img src="pdf.png" title="PDF" alt="PDF" /> }
        </PDFDownloadLink>
         :
        <React.Fragment/>
        }
    </div >
);

效果很好,但是如果我回到家,有时我会收到这个错误:

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

有人可以帮我吗?


我尝试了您指定的解决方案,但我仍然遇到同样的错误。 我的 "loadPDF" 值为 true,这是因为我收到了 AXIOS 的响应。

如果在收到 AXIOS 的响应后,我等待几秒钟,然后用浏览器返回,则没有此错误。

如果在 AXIOS 回复后我使用浏览器返回,我会收到此错误消息。 这是因为 Component PDF 内部有很多逻辑,可能需要一些时间。

我必须在 ComponentePDF 中工作吗?

【问题讨论】:

标签: reactjs react-native react-router react-hooks


【解决方案1】:

发生的情况是,React 在组件卸载时尝试更新状态,所以我们需要在组件卸载时取消 Axios 请求。

为了简单起见,我将从 props 中解构 id。另外,您可以查看 Axios 的 Cancellation 文档以了解如何操作,但我将为您提供以下示例:

useEffect(() => {
    const url = '';

    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();

    axios
      .get(url, {
        params: { id },
        cancelToken: source.token,
      })
      .then((response) => {
        setPDF(true);
        setUtente(response);
      })
      .catch((err) => {
        setPDF(false);
        setUtente(null);
      });

    return () => source.cancel();
  }, [id]);

【讨论】:

    猜你喜欢
    • 2023-02-11
    • 1970-01-01
    • 2021-07-01
    • 2020-11-21
    • 2020-03-29
    • 1970-01-01
    • 2019-11-09
    • 2019-05-30
    相关资源
    最近更新 更多