控制台警告:Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects

现象:

  • ajax读取一个本地文本文件,Chrome控制台报错:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

虽然这只是一个警告,并不影响程序执行,但看上去着实很烦人。
原本的代码如下:

      let xhr = new XMLHttpRequest();
      xhr.open(
        "GET",
        "/static/test.txt",
        false
      ); 
      xhr.overrideMimeType("text/html;charset=utf-8"); //默认为utf-8
      xhr.send(null);
      console.log(xhr.responseText)

这个问题也不仅限于读取本地文件,网上搞讨论的人也比较多,我试了很多未果。

解决:

  • 后来改用axios取代原生的XMLHttpRequest,嘿嘿,果然,问题解决了。
  • 代码如下,换用这段代码后,控制台不再出现那个警告:
      this.axios({
    
     url: "/static/test.txt", baseURL: "" }).then(
        (response) => {
    
    
          if (response.data) {
    
    
            console.log(response.data);
          }
        }
      );
    },

后级:

猜你喜欢

转载自blog.csdn.net/rockage/article/details/121409599