警告:setState(...):只能在新的 reactjs 应用程序上更新已安装或正在安装的组件

Warning: setState(...): Can only update a mounted or mounting component on a new reactjs app

我有以下组件:

import React, { Component } from 'react';

import { Row, Col } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper.js';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data: []
    };
    this.fetchData();
  }

  getValues() {
    adalApiFetch(fetch, '/values', {})
      .then((response) => {

        // This is where you deal with your API response. In this case, we            
        // interpret the response as JSON, and then call `setState` with the
        // pretty-printed JSON-stringified object.
        response.json()
          .then((responseJson) => {
            this.setState({ data: JSON.stringify(responseJson, null, 2) })
          });
      })
      .catch((error) => {

        // Don't forget to handle errors!
        console.error(error);
      })

  }

  fetchData() {
    try {
        const data =  this.getValues();
        !this.isCancelled && this.setState({ data });
    } catch(error) {
        console.log(error);
    }
  }

  render() {
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;
    const radioStyle = {
        display: 'block',
        height: '30px',
        lineHeight: '30px'
      };
      const plainOptions = ['Apple', 'Pear', 'Orange'];
      const options = [
        { label: 'Apple', value: 'Apple' },
        { label: 'Pear', value: 'Pear' },
        { label: 'Orange', value: 'Orange' }
      ];
      const optionsWithDisabled = [
        { label: 'Apple', value: 'Apple' },
        { label: 'Pear', value: 'Pear' },
        { label: 'Orange', value: 'Orange', disabled: false }
      ];

    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
        <Row style={rowStyle} gutter={gutter} justify="start">
          <Col md={12} sm={12} xs={24} style={colStyle}>
            <Box
              title={<IntlMessages id="pageTitles.TenantAdministration" />}
              subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
            >
              <ContentHolder>
                  <ul>
                    {data && data.map(item => (
                        <li>{item.name}</li>
                    ))}
                  </ul>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

和我的 adalconfig

import { AuthenticationContext, adalFetch, withAdalLogin } from 'react-adal';

export const adalConfig = {
  tenant: 'aa-c220-48a2-a73f-1177fa2c098e',
  clientId: 'aa-bd54-456d-8aa7-f8cab3147fd2',
  endpoints: {
    api:'aa-abaa-4519-82cf-e9d022b87536'
  },
  'apiUrl': 'https://webapi-app.azurewebsites.net/api',
  cacheLocation: 'localStorage'
};

export const authContext = new AuthenticationContext(adalConfig);

export const adalApiFetch = (fetch, url, options) =>
  adalFetch(authContext, adalConfig.endpoints.api, fetch, adalConfig.apiUrl+url, options);

export const withAdalLoginApi = withAdalLogin(authContext, adalConfig.endpoints.api);

并且控制台中的错误是:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmountedA component. This is a no-op.

发生这种情况是因为您正在调用 this.fetchData()(依次在构造函数中调用 this.getValues() )。但是 setState() 应该只在组件渲染后调用。

最好在 componentDidMount() 中调用 this.fetchData()。

在您的 render() 函数中添加:

      <ContentHolder>
 <ul> 
{data.length && data.map(item => ( <li>{item.name}</li> ))} 
</ul> 
</ContentHolder>

**data.length 而不是数据,因为空数组的计算结果始终为真。