反应警告:无法在未安装的组件上调用setState(或forceUpdate)

时间:2018-07-31 08:51:58

标签: javascript reactjs axios

我有2个组成部分:
订单-获取一些数据并显示。
ErrorHandler-如果服务器上发生某些错误,则会显示一个模式并显示一条消息。
ErrorHandler组件正在扭曲订单组件

我正在使用axios包在Orders组件中加载数据,并且我使用axios拦截器来设置有关错误的状态,并在卸载组件后弹出。

当我前后导航到订单组件时,有时会在控制台中出现错误:

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.
    in Orders (at ErrorHandler.jsx:40)
    in Auxiliary (at ErrorHandler.jsx:34)
    in _class2 (created by Route)

我试图通过我以前的案例React Warning: Can only update a mounted or mounting component解决此问题,但在这里,检查员无法制作axios令牌。有人解决过这个问题吗?

这是我的组件:

订单:

import React, { Component } from 'react';
import api from '../../api/api';
import Order from '../../components/Order/Order/Order';
import ErrorHandler from '../../hoc/ErrorHandler/ErrorHandler';

class Orders extends Component {
    state = {
        orders: [],
        loading: true
    }

    componentDidMount() {
        api.get('/orders.json')
            .then(response => {
                const fetchedOrders = [];
                if (response && response.data) {
                    for (let key in response.data) {
                        fetchedOrders.push({
                            id: key,
                            ...response.data[key]
                        });
                    }
                }
                this.setState({ loading: false, orders: fetchedOrders });
            })
            .catch(error => {
                this.setState({ loading: false });
            });
    }

    render() {
        return (
            <div>
                {this.state.orders.map(order => {
                    return (<Order
                        key={order.id}
                        ingrediencies={order.ingrediencies}
                        price={order.price} />);
                })}
            </div>
        );
    }
}

export default ErrorHandler(Orders, api);

ErrorHandler:

import React, { Component } from 'react';
import Auxiliary from '../Auxiliary/Auxiliary';
import Modal from '../../components/UI/Modal/Modal';

const ErrorHandler = (WrappedComponent, api) => {
    return class extends Component {
        requestInterceptors = null;
        responseInterceptors = null;
        state = {
            error: null
        };

        componentWillMount() {
            this.requestInterceptors = api.interceptors.request.use(request => {
                this.setState({ error: null });
                return request;
            });
            this.responseInterceptors = api.interceptors.response.use(response => response, error => {
                this.setState({ error: error });
            });
        }

        componentWillUnmount() {
            api.interceptors.request.eject(this.requestInterceptors);
            api.interceptors.response.eject(this.responseInterceptors);
        }

        errorConfirmedHandler = () => {
            this.setState({ error: null });
        }

        render() {
            return (
                <Auxiliary>
                    <Modal
                        show={this.state.error}
                        modalClosed={this.errorConfirmedHandler}>
                        {this.state.error ? this.state.error.message : null}
                    </Modal>
                    <WrappedComponent {...this.props} />
                </Auxiliary>
            );
        }
    };
};

export default ErrorHandler;

3 个答案:

答案 0 :(得分:5)

我认为这是由于异步调用触发了setState,即使未安装组件也可能发生。为了防止这种情况的发生,您可以使用某种标志:

  state = {
    isMounted: false
  }
  componentDidMount() {
      this.setState({isMounted: true})
  }
  componentWillUnmount(){
      this.state.isMounted = false
  }

然后用if包裹您的setState调用:

if (this.state.isMounted) {
   this.setState({ loading: false, orders: fetchedOrders });
}

答案 1 :(得分:2)

您不能在componentWillMount方法中设置状态。尝试重新考虑您的应用程序逻辑并将其移至另一个生命周期方法。

答案 2 :(得分:0)

我认为根本原因与我昨天回答的原因相同,您需要“取消” unmount上的请求,我看不出您是否为{{ 1}}组件。

关于错误处理的注释,它看起来过于复杂,我绝对鼓励您查看React提供的ErrorBoundaries。您不需要具有api.get()或更高阶的元素。

对于ErrorBoundaries,React引入了一种生命周期方法,称为:Orders。 您可以使用它来将interceptors代码简化为:

componentDidCatch

然后在您的ErrorHandler组件中:

class ErrorHandler extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true, errorMessage : error.message });
  }

  render() {
    if (this.state.hasError) {
      return <Modal 
                    modalClosed={() => console.log('What do you want user to do? Retry or go back? Use appropriate method logic as per your need.')}>
                    {this.state.errorMessage ? this.state.errorMessage : null}
                </Modal>
    }
    return this.props.children;
  }
}

并在您的代码中将其用作:

Orders