【问题标题】:Error: 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错误:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏
【发布时间】:2020-06-27 11:23:51
【问题描述】:

我收到上述错误,我不知道如何处理。

我有一个组件。在 render() 中,我循环遍历一个数组并放置另一个组件并将值解析给该组件,如下所示:

render() {
  let allProducts = this.state.products.map((product, i) => {
    return (
      <div key={product.article}>
         ...
           <PriceStock value={product.article} />
         ...
      </div>
    )
  })
}

在 PriceStock 组件中,我使用 axios 获取一些数据,如下面的代码:

export default class PriceStock extends React.Component {

constructor(props) {
    super(props);
    this.state = ({
        buttoprice: ''
    })
    this.getPriceAndStock = this.getPriceAndStock.bind(this)
}

getPriceAndStock(articleNo) {
    return axios.post('LINK_TO_URL', {
        articleNo: articleNo
    }).then(result => {
        return result.data
    })
}

async componentDidMount() {
    let pricestock;
    pricestock = await this.getPriceAndStock(this.props.value)
    let bruttoPrice = PRICE_TO_PARSE_TO_THE_STATE;
    this.setState({ buttoprice: bruttoPrice })
}

render() {

    return (
        <div >
            {this.state.buttoprice}
        </div>
    );
}

}

当我尝试在componentDidMount中设置状态时似乎发生了错误,有什么建议吗?

【问题讨论】:

标签: reactjs


【解决方案1】:

这是一个错误,因为您在初始化之前更新状态 在构造函数中执行加载活动是正确的方法

getPriceAndStock(orderNumber, articleNo) {
  return axios.post('LINK_TO_URL', {
      orderNr: orderNumber, vareNr: articleNo
  }).then(result => {
      return result.data
  })
}

constructor() {
  this.getPriceAndStock(this.props.value)
  .then(pricestock=>{
    let bruttoPrice = PRICE_TO_PARSE_TO_THE_STATE;
    this.state({ buttoprice: bruttoPrice })
  })
  .catch(console.log)

}

【讨论】:

  • 然后我得到一个 this.state is not a function 错误? :-)
  • 你能不能分享你的整个组件很难知道你在哪里调用constructor()
  • 我刚刚编辑了我的问题,所以孔组件正在显示:-)
  • 您的代码很好,问题是您在收到来自 API 的响应后调用 setState 函数,直到您收到响应,您的组件以某种方式被卸载,这会导致此问题,因此请确保您的组件已安装,而设置状态
  • 谢谢你,但它真的很奇怪:-)
【解决方案2】:

在这个问题中找到答案:https://github.com/material-components/material-components-web-react/issues/434

这让我想起了关于另一个 stackoverflow 问题的评论。

【讨论】:

    猜你喜欢
    • 2021-08-09
    • 2021-11-14
    • 2019-12-31
    • 2020-09-18
    • 2021-05-14
    • 2020-01-24
    • 2021-06-29
    • 2018-12-17
    • 2021-11-25
    相关资源
    最近更新 更多