gpt4 book ai didi

reactjs - 组件DidMount : Can't call setState (or forceUpdate) on an unmounted component

转载 作者:行者123 更新时间:2023-12-03 13:29:08 24 4
gpt4 key购买 nike

我正在 componentDidMount 中获取数据并更新状态,并且出现了著名的警告:

Warning: Can't call setState (or forceUpdate) 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.

我的代码如下:

componentDidMount() {
let self = this;

let apiBaseUrl = Config.serverUrl;
axios.get( apiBaseUrl + '/dataToBeFetched/' )
.then( function(response) {
self.setState( { data: response.data } );;
} );
}

导致此警告的原因是什么?获取数据和更新状态的最佳方法是什么?

最佳答案

根据之前的回答,我做了以下工作,效果很好:

constructor(props) {
this.state = {isMounted: false}
}

componentDidMount() {
let apiBaseUrl = Config.serverUrl;
this.setState( { isMounted: true }, () => {
axios.get( apiBaseUrl + '/dataToBeFetched/' )
.then( (response) => { // using arrow function ES6
if( this.state.isMounted ) {
this.setState( { pets: response.data } );
}
} ).catch( error => {
// handle error
} )
} );
}

componentWillUnmount() {
this.setState( { isMounted: false } )
}

另一个更好的解决方案是在卸载中取消请求,如下所示:

constructor(props) {
this._source = axios.CancelToken.source();
}

componentDidMount() {
let apiBaseUrl = Config.serverUrl;
axios.get( apiBaseUrl + '/dataToBeFetched/', { cancelToken: this._source.token } )
.then( (response) => { // using arrow function ES6
if( this.state.isMounted ) {
this.setState( { pets: response.data } );
}
} ).catch( error => {
// handle error
} );
}

componentWillUnmount() {
this._source.cancel( 'Operation canceled due component being unmounted.' )
}

关于reactjs - 组件DidMount : Can't call setState (or forceUpdate) on an unmounted component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50396375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com