【问题标题】:Warning: Can't perform a React state update on an unmounted component. useEffect cleanup function警告:无法对未安装的组件执行 React 状态更新。 useEffect 清理功能
【发布时间】:2019-10-07 20:49:07
【问题描述】:

如何解决这个问题?

//ReviewProductDetail.jsx :

第一次从这个组件获取页面

import React, { useEffect, useState } from 'react';
import RatingCardProductDetail from '../../components/RatingCardProductDetail';
import "./style.sass";
import FilterReviewProductDetail from '../../components/FilterReviewProductDetail';
import { Row, Col, Pagination, Spin } from 'antd';
import LatestReview from '../../components/LatestReview';
import strings from '../../localization/localization';
import Product from '../../repository/Product';

function ReviewProductDetail({ productId }) {
    const [reviewRatingDetail, setReviewRatingDetail] = useState({})
    const [reviewRating, setReviewRating] = useState([])
    const [notFound, setNotFound] = useState(false)
    const [loading,setLoading] = useState(false)

    useEffect(() => {
        getReviewRatingDetail();
        getReviewRating();
    }, [])


    async function getReviewRatingDetail() {
        let reviewRatingDetail = await Product.reviewRatingDetail({
            productId: productId
        })
        if (reviewRatingDetail.status === 200) {
            setReviewRatingDetail(reviewRatingDetail)
        } else {
            setReviewRatingDetail({})
        }
    }

    async function getReviewRating() {
        let reviewRating = await Product.reviewRating({
            productId: productId,
            loading: setLoading
        })
        if (reviewRating.status === 200) {
            setReviewRating(reviewRating)
            setNotFound(false)
        } else {
            setReviewRating([])
            setNotFound(true)
        }
    }

    return (
        <Spin spinning={loading}>
            <div className="mp-review-product-detail">
                {notFound ?
                    <div className="mp-product-detail__not-found">
                        <span>
                            Belum ada ulasan untuk produk ini
                        </span>
                    </div> :
                    <React.Fragment>
                        <RatingCardProductDetail reviewRatingDetail={reviewRatingDetail} />
                        <Row>
                            <Col md={17} offset={3}>
                                <div className="mp-review-product-detail__filter">
                                    <FilterReviewProductDetail />
                                </div>
                            </Col>
                        </Row>
                        <h3>{strings.latest_review}</h3>
                        {reviewRating.review &&
                            reviewRating.review.map((review, i) => {
                                return <LatestReview key={i} review={review} />
                            })}
                        <Pagination
                            className="mp-pagination-review-product-detail"
                            defaultCurrent={1}
                            total={5} />
                    </React.Fragment>}
            </div>
        </Spin>
    );
}; 

export default ReviewProductDetail;

那么这是一个调用数据API的组件,

async function reviewRatingDetail(props) {
  const loading = props.loading ? props.loading : function () { };
  const productId = props.productId;
  // const decodeURL = decodeURI(productId)
  const idProduct = productId.replace(/ /g, '')
  let response = "";
  loading(true);
  try {
    response = await apiGetWithoutToken(`${PATH_PRODUCT.PRODUCT}/${idProduct}/${PATH_PRODUCT.PRODUCT_REVIEW_RATING_DETAIL}`);
    response = jmespath.search(response, productsReviewDetail);
    loading(false);
  } catch (error) {
    response = jmespath.search(error.response, productsReviewDetail);
    loading(false);
  }
  return response;
}

async function reviewRating(props) {
  const loading = props.loading ? props.loading : function () { };
  const productId = props.productId;
  //const decodeURL = decodeURI(productId);
  const idProduct = productId.replace(/ /g, '');
  let response = "";
  loading(true);
  try {
    response = await apiGetWithoutToken(`${PATH_PRODUCT.PRODUCT}/${idProduct}/${PATH_PRODUCT.PRODUCT_REVIEW}`);
    response = jmespath.search(response, productsReview);
    loading(false);
  } catch (error) {
    response = jmespath.search(error.response, productsReview);
    loading(false);
  }
  return response;
}

/** 无令牌服务 api getWithoutToken */


export const apiGetWithoutToken = (url, params = null) => {
  return serviceWithoutToken().get(url, {
    params: params
  });
};

export const serviceWithoutToken = () => axios.create({
  baseURL: REACT_APP_API_SERVICE,
  timeout: 60 * 4 * 1000,
  headers: {
    "Content-Type": `application/json`,
  }
});

我想请教您,如何摆脱这些错误标记。请直接举个例子谢谢

【问题讨论】:

  • 请详细说明您尝试了什么以及究竟是什么问题。
  • 我想消除上图的错误提示,怎么做?
  • @PutraIrawan 但是什么试过了吗?发生这种情况是因为您的代码在 卸载后调用了状态变换器。您是否调查过为什么/如何发生这种情况?您的 useEffect 钩子是否返回清理函数?

标签: javascript reactjs promise


【解决方案1】:

尝试使用Effect添加这个:

useEffect(() => {
    getReviewRatingDetail();
    getReviewRating();
}, [productId])

或在整个函数 ReviewProductDetail 上使用 useCallback (https://reactjs.org/docs/hooks-reference.html#usecallback)

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 2020-11-22
    • 2023-03-06
    • 2021-02-24
    • 1970-01-01
    • 2021-03-27
    • 2019-09-11
    相关资源
    最近更新 更多