Axios CancelToken不适用于POST方法

时间:2019-12-28 10:27:54

标签: reactjs express asynchronous post axios

我正在使用axios,我想进行实时搜索。当onChange时,我使用 POST 方法调用异步搜索功能。

我的搜索功能:

  search = async val => {
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    this.setState({loading: true})

    try {
      const res = await axios.post('/api/data/search', {value: val}, {cancelToken: source.token});
      source.cancel('Operation canceled by the user.')
      const results = await res.data.results;
      this.setState({ results, loading: false }, () => console.log(results))
    } catch (error) {
      console.log("Error")
      this.setState({ results, loading: false })
    }
  }

但是取消功能不起作用。我使用的是axios文档。.问题出在哪里?

在axios文档中的用法:https://github.com/axios/axios#cancellation

示例代码:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

    axios.post('/user/12345', {
      name: 'new name'
    }, {
      cancelToken: source.token
    })

    // cancel the request (the message parameter is optional)
    source.cancel('Operation canceled by the user.');

所有查询有效。

enter image description here

1 个答案:

答案 0 :(得分:0)

您可能需要稍作更新以触发取消之前的逻辑

search = async val => {
  if (this.state.source) { // checks if there's any pending request
    this.state.source.cancel('Operation canceled by the user.') // if so, cancel it
  }

  const CancelToken = axios.CancelToken;
  const source = CancelToken.source();

  this.setState({loading: true, source}) // store the source in the state

  try {
    const res = await axios.post('/api/data/search', {value: val}, {cancelToken: source.token});
    const results = await res.data.results;
    this.setState({ results, loading: false, source: undefined }, () => console.log(results)) // set the source to undefined
  } catch (error) {
    console.log("Error")
    this.setState({ results, loading: false })
  }
}