reactjs - 无法对未安装的组件执行 React 状态更新。React、redux 和 useEffect 的问题
问题描述
我有一个使用这样的钩子的 React 组件:
const myComponent = (props) => {
useEffect(() => {
FetchData()
.then(data => {
setState({data: data});
}
// some other code
}, []);
//some other code and render method...
}
fetchData 负责使用 axios 并从 API 获取数据:
const FetchData = async () => {
try {
res = await myApiClient.get('/myEndpoint);
} catch (err) {
console.log('error in FetchData');
res = err.response
}
}
最后 myApiClient 是在外部定义的。我必须使用此设置才能使用不同的 API...
import axios from "axios";
axios.defaults.headers.post["Content-Type"] = "application/json";
const myApiClient = axios.create({
baseURL: process.env.REACT_APP_API1_BASEURL
});
const anotherApiClient = axios.create({
baseURL: process.env.REACT_APP_API2_BASEURL
});
export {
myApiClient,
anotherApiClient
};
使用此设置,我收到警告
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.
我用谷歌搜索了一下,我看到了一些关于如何清理来自 useEffect 的请求的建议,就像这样,但我的 axios 是在外部定义的。那么如何使用此设置发送取消?
此外,该应用程序正在使用 redux,不确定它是否以某种方式涉及。
欢迎任何其他避免错误的建议。
解决方案
您可以为此使用defer
from :rxjs
const FetchData = () => {
try {
return myApiClient.get("/myEndpoint");
} catch (err) {
console.log("error in FetchData");
return err.response;
}
};
const myComponent = (props) => {
useEffect(() => {
const subscription = defer(FetchData()).subscribe({
next: ({
data
}) => {
setState({
data: data
});
},
error: () => {
// error handling
},
complete: () => {
// cancel loading state etc
}
});
return () => subscription.unsubscribe();
}, []);
}
推荐阅读
- c# - 如何在 xamarin Android 中下载(从 URL)带有按钮的 apk?
- python - SubConverterFileIOException - 音乐 21 show()
- django - 如何使用 get_context_data 获取 id?
- jquery - 选中/取消选中剃刀页面中的单选按钮时如何隐藏和显示文本框?
- flutter - vscode 中的 dart.closingLabels 问题
- matlab - 如何对实验数据进行非线性数据拟合
- ruby-on-rails - 正则表达式查找不在 URL 路径中的单词实例
- spring-boot - 无法将工件 org.springframework.boot:spring-boot-starter-parent:pom:2.1.5.RELEASE 从/转移到 nexus
- hyperledger-fabric - Hyperledger Fabric 中的会员服务提供商 (MSP) 到底是什么?
- android - 如何使用 Kotlin 以编程方式设置工具栏的边距