reactjs - Aborted fetch 仍在调用“then”函数?
问题描述
我有一个反应组件,它在挂载/卸载时调用 fetch/abort,当我试图将 fetch 函数移动到一个单独的类时,即使在中止 fetch 请求之后,“then”函数也会继续调用,因此会打印“Not Aborted”文本到控制台。
它看起来像这样:
反应组件
class ReactComponent extends Component {
constructor(props) {
super(props);
this.TodoService = new TodoService();
}
componentDidMount() {
this.TodoService.fetch().then(res => {
console.log("Not Aborted");
});
}
componentWillUnmount() {
this.TodoService.abort();
}
}
待办事项服务
class TodoService {
constructor() {
this.controller = new AbortController();
this.signal = this.controller.signal;
}
handleErrors(response) {
if (response.ok) {
return response;
}
throw Error(response.statusText);
}
fetch() {
return fetch(`todos`, {
signal: this.signal
})
.then(this.handleErrors)
.then(res => res.json())
.catch(err => console.error(err));
}
abort() {
this.controller.abort();
}
}
解决方案
你也可以试试这个:
fetch() {
return fetch(`todos`,
{signal: this.signal},
this.controller.abort()
)
.then(this.handleErrors)
.then(res => res.json())
.catch(err => console.error(err));
}
推荐阅读
- javascript - 如何更改在另一个功能中关闭的滑块的图像?
- c++ - 使用 ifstream 读取坐标文件,同时忽略标题并写入数组
- node.js - npm install 抛出异常
- styled-components - styled-component 是否可以封装成内联样式?
- java - 如何正确关闭输入流?
- spring - 如何在 Spring JPA 的 CriteriaBuilder 中按字符串中的整数排序?
- javascript - 仅 6 次将 API POST 获取到 Node-js
- python - Pycharm 解释器设置
- python - ARIMA:在不更新模型的情况下预测下一步
- rust - 对于基于代理的模拟,如何以高效的方式规避“不能一次多次借用 `*self` 作为可变变量”?