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:
componentWillUpdate (Causing Crashes) First, let's break down why this is happening:
componentWillUpdatetriggers 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 triggerscomponentWillUpdateonce more. This creates an infinite loop that chokes your browser.- On top of that,
componentWillUpdateis 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
componentDidMountto fetch initial data once when the component mounts. - Use
componentDidUpdateonly 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; }); }
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

