You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+JS中componentWillUpdate调用过频致应用崩溃求助

Hey there, let's tackle these two issues you're facing—they're both rooted in how you're managing data fetching and state updates with React and Mobx. Here's a step-by-step fix for each:

1. Fixing the Infinite Loop in componentWillUpdate (Causing Crashes)

First, let's break down why this is happening:

  • componentWillUpdate triggers every time your component is about to re-render. When you fetch data and update the Mobx store inside it, that store update causes the component to re-render again... which triggers componentWillUpdate once more. This creates an infinite loop that chokes your browser.
  • On top of that, componentWillUpdate is considered an unsafe lifecycle method in modern React—you should avoid using it entirely.

The Fix:

Replace componentWillUpdate with safer lifecycle methods and add guardrails to prevent unnecessary requests:

  • Use componentDidMount to fetch initial data once when the component mounts.
  • Use componentDidUpdate only when specific conditions change (to avoid re-fetching on every render).
  • Extract the fetch logic into a reusable function for cleaner code.

Here's the updated code:

componentDidMount() {
  // Fetch trades once when the component first loads
  this.fetchTrades();
}

componentDidUpdate(prevProps) {
  // Only re-fetch if a relevant value changes (example: a flag in your store)
  // Adjust this condition based on what should trigger a refresh (e.g., after deletion)
  if (this.props.store.shouldRefreshTrades !== prevProps.store.shouldRefreshTrades) {
    this.fetchTrades();
    // Reset the flag after fetching (if using this approach)
    this.props.store.shouldRefreshTrades = false;
  }
}

fetchTrades() {
  // Optional: Add a loading flag to prevent duplicate requests
  if (this.props.store.isFetching) return;
  this.props.store.isFetching = true;

  axios.get(`http://localhost:8091/trade`)
    .then(res => {
      this.props.store.arr = res.data;
    })
    .catch(err => {
      console.error('Failed to load trades:', err);
    })
    .finally(() => {
      this.props.store.isFetching = false;
    });
}
2. Fixing the "Delete Requires Manual Refresh" Issue

The problem here is that after deleting a trade, you're not telling your Mobx store to update the list—so the component has no idea the data changed.

Two Simple Fixes:

Option 1: Re-fetch the full list after deletion (simple, reliable)

After your delete request succeeds, call the same fetchTrades() function we created above to get the fresh data from the backend:

handleDelete = (tradeId) => {
  axios.delete(`http://localhost:8091/trade/${tradeId}`)
    .then(() => {
      // Delete succeeded—refresh the trade list
      this.fetchTrades();
    })
    .catch(err => {
      console.error('Failed to delete trade:', err);
      // Show an error message to the user here if needed
    });
}

Option 2: Update the store directly (more efficient)

Instead of re-fetching the entire list, filter out the deleted trade from the store's array once the delete request succeeds. This avoids an extra network call:

handleDelete = (tradeId) => {
  axios.delete(`http://localhost:8091/trade/${tradeId}`)
    .then(() => {
      // Remove the deleted trade from the store's array
      this.props.store.arr = this.props.store.arr.filter(trade => trade.id !== tradeId);
    })
    .catch(err => {
      console.error('Failed to delete trade:', err);
      // If deletion fails, you might want to revert the UI change or notify the user
    });
}

Quick Note:

Make sure your Mobx store's arr property is marked as observable (using @observable or makeObservable) so that changes to it automatically trigger component re-renders.


内容的提问来源于stack exchange,提问作者AConsumer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:03:25