警告:无法在 React 本机中对卸载的组件执行 React 状态更新



我正在从axios获取数据。但有时数据会到来,而有些数据最初并没有显示出来。

获取具体薪资api.js:---

const AllSpecificSalaryAPI = (yearMonthFilter) => {
const [specificAllAPIData, setAllSpecificAPIData] = useState("");
const loginAuthToken = useSelector(
(state) => state.loginAuthTokenReducer.loginAuthToken
);
//NOTE:taking oved input and company selection code for dynamic parameter
const companyValue = useSelector(
(state) => state.changeCompanyReducer.company
);
const companyCode = companyValue[0];
const employeeId = companyValue[1];
useEffect(() => {
axios
.get(GET_ALL_SPECIFIC_SALARY, {
params: {
hev: companyCode,
year_month: yearMonthFilter,
oved: employeeId,
},
headers: {
Authorization: `Bearer ${loginAuthToken}`,
},
})
.then((response) => response.data)
.then((data) => setAllSpecificAPIData(data))
.catch((error) => {
if (error.status === 401) {
//NOTE: handling token expire
return ExpireAlertRestart();
} else {
Alert.alert(error.message);
}
});
}, []);
return {
specificAllAPI: specificAllAPIData,
};
};
export default AllSpecificSalaryAPI;

我收到了警告信息。

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.
at [native code]:null in dispatchAction
at src/api/get-specific-salary-api.js:32:12 in axios.get.then.then$argument_0

如何解决此警告消息?

在你的useEffect中,像这样清理你的状态:

const [specificAllAPIData, setAllSpecificAPIData] = useState(null);
useEffect(() => {
return () => {
setAllSpecificAPIData(null);
};
}, []);

请在这里查看有关useEffect如何工作的更好解释

您之所以会出现这种情况,是因为即使组件已卸载,组件也会尝试update the state

为了解决这个问题,您可以使用一个指标变量来告诉组件的卸载。在卸载时,它将拦截其间的状态更新请求并取消该请求。

let hasUnmounted = false;
useEffect(() => {
axios
.get(GET_ALL_SPECIFIC_SALARY, {
params: {
hev: companyCode,
year_month: yearMonthFilter,
oved: employeeId,
},
headers: {
Authorization: `Bearer ${loginAuthToken}`,
},
})
.then((response) => response.data)
.then((data) => {
if (hasUnmounted) return;
setAllSpecificAPIData(data)
})
.catch((error) => {
if (hasUnmounted) return;
if (error.status === 401) {
//NOTE: handling token expire
return ExpireAlertRestart();
} else {
Alert.alert(error.message);
}
});
return () => {
hasUnmounted = true;
}
}, []);

请检查此链接以了解实施情况:https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/updateErr.js

注意:转到codesandbox's browser中的https://ikqdn.csb.app/err

最新更新