reactjs - 如何解决 ReactJs Can't perform a React state update on an unmounted component
问题描述
当我尝试使用反应路由器时出现此错误,我注意到在我的 reactjs 环境中一切正常,但是当我运行 npm run build file 时反应路由器不起作用,
这是完整的错误,我看到我的控制台需要修复它。
index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in TextTypeEffect (at carousel.js:8)
in div (at carousel.js:7)
in div (at carousel.js:6)
in Carousel (at App.js:71)
in Home (at App.js:41)
解决方案
当您的组件在组件卸载后尝试设置状态时会发生这种情况,因此您需要取消订阅状态更新componentWillUnmount()
下面是类组件的示例代码
import React, { Component } from 'react';
class MyComponent extends Component {
_isMounted = false;
componentDidMount() {
this._isMounted = true;
}
componentWillUnmount = () => this._isMounted = false;
setState = (state, callback) => this._isMounted && super.setState(state, callback);
}
推荐阅读
- sql - 我正在尝试使用聚合函数来整合数据,但我不确定我做错了什么
- android - Xamarin.Forms 样式 BarBackgroundColor 透明
- java - java - 如何在Java流中使用startsWith方法?
- java - OAuth2Client 每次都返回相同的令牌
- continuous-integration - 将 Gitlab CI 工件上传到 Gitlab 外部的存储中
- ruby-on-rails - 使用 grouped_options_for_select 设置默认值,使用 f.select
- java - 解释如何限制用户通过 Web 应用程序登录并仅在 Java 和 Spring 框架中允许通过移动应用程序登录?
- java - 在多个 EditText 字段中显示 Drawable
- sql - 匹配代码并复制列
- python - Tornado websocket 消息没有收到