Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

reactjs - React useEffect: "Can't perform a React state update on an unmounted component" with Redux

I am building an e-commerce website and I have a reducer to calculate the total price, but when I submit the order in the end I get this error

Warning: 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. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

The reducer

export const totalReducer = (total = 0, action) => {
  switch (action.type) {
    case CALCULATE_TOTAL:
      for (let i = 0; i < action.data.length; i++) {
        total += parseFloat(action.data[i].price) * action.data[i].count;
      }
      return total;
    default:
      return 0;
  }
};

The action

export const calculateTotal = (data) => {
  return {
    type: CALCULATE_TOTAL,
    data,
  };
};

I am using a useEffect to change the total price

 useEffect(() => {
    dispatch(calculateTotal(foods));
  }, [foods]);

This doesn't trigger any warnings, but when I move to the checkout page and submit the form below I get the error after getting redirected to /submitted, and the website starts lagging.

 const total = useSelector((state) => state.totalReducer);

  const submitHandler = (e) => {
    e.preventDefault();
    history.push("/submitted");
  };

  return (
      <h2 className="total-price">Total Price = {total}</h2>
 <form className="information-form" onSubmit={submitHandler} action="">
//////////////
</form>

How can I clean useDispatch in Redux and what's causing the error this late in the process?

question from:https://stackoverflow.com/questions/65932951/react-useeffect-cant-perform-a-react-state-update-on-an-unmounted-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...