首页 > 解决方案 > 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();
  }
}

标签: reactjsfetchabort

解决方案


你也可以试试这个:

fetch() {

     return fetch(`todos`, 
        {signal: this.signal}, 
        this.controller.abort()
   )
  .then(this.handleErrors)
  .then(res => res.json())
  .catch(err => console.error(err));
}

推荐阅读