简体   繁体   English

Axios 请求超时

[英]Timeout on Axios Requests

Our site currently has a filter feature that fetches new data via axios depending on what is being filtered.我们的网站目前有一个过滤器功能,可以根据过滤的内容通过 axios 获取新数据。

The issue is that the filter is done on real time and every change made via react causes an axios request.问题是过滤器是实时完成的,通过 react 所做的每一次更改都会导致 axios 请求。

Is there a way to put a timeout on the axios request so that I only fetch the last state?有没有办法在 axios 请求上设置超时,以便我只获取最后一个状态?

I would suggest using debounce in this case to trigger API call after a specified millisecond of user input.我建议在这种情况下使用debounce在用户输入的指定毫秒后触发 API 调用。

But just in case you need to add a timeout during axios call, this can be achieved like -但以防万一您需要在axios调用期间添加超时,这可以像 -

instance.get('/longRequest', {
  timeout: 5000
});

The problem has two parts.问题有两部分。

The first part is debouncing and is default for event listeners that can be triggered often, especially if their calls are expensive or may cause undesirable effects.第一部分是 debounce,并且是可以经常触发的事件侦听器的默认设置,尤其是当它们的调用成本高昂或可能导致不良影响时。 HTTP requests fall into this category. HTTP 请求属于这一类。

The second part is that if debounce delay is less than HTTP request duration (this is true for virtual every case), there still will be competing requests, responses will result in state changes over time, and not necessarily in correct order.第二部分是如果 debounce 延迟小于 HTTP 请求持续时间(对于虚拟每种情况都是如此),仍然会有竞争请求,响应会随着时间的推移导致状态变化,并且不一定是正确的顺序。

The first part is addressed with debounce function to reduce the number of competing requests, the second part uses Axios cancellation API to cancel incomplete requests when there's a new one, eg:第一部分使用 debounce 函数来减少竞争请求的数量,第二部分使用 Axios取消 API在有新请求时取消未完成的请求,例如:

  onChange = e => {
    this.fetchData(e.target.value);
  };

  fetchData = debounce(query => {
    if (this._fetchDataCancellation) {
      this._fetchDataCancellation.cancel();
    }

    this._fetchDataCancellation = CancelToken.source();

    axios.get(url, {
      cancelToken: this._fetchDataCancellation.token
    })
    .then(({ data }) => {
      this.setState({ data });
    })
    .catch(err => {
      // request was cancelled, not a real error
      if (axios.isCancel(err))
        return;

      console.error(err);
    });
  }, 200);

Here is a demo .这是一个演示

From this axios issue (Thanks to zhuyifan2013 for giving the solution), I've found that axios timeout is response timeout not connection timeout .从这个axios 问题(感谢zhuyifan2013提供解决方案),我发现axios timeoutresponse timeout而不是connection timeout

Please check this answer请检查这个答案

您还可以将axios.defaults用作所有请求的常规设置:

axios.defaults.timeout = 5000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM