[JavaScript] XMLHttpRequest同期処理するとエラーなる場合対処

2 min read
hiroweb developer

問題

以下のようにopen()の第 3 引数をfalseにし、非同期処理から同期処理へ変更した。

xhr.open("GET", "https://example.jp/rest-api/posts.json", false);
xhr.responseType = "json";
xhr.send();

すると実行時に以下のようなエラーが発生してしまった。

Uncaught DOMException: Failed to set the 'responseType' property on 'XMLHttpRequest': The response type cannot be changed for synchronous requests made from a document.

解決方法

エラーにある通り、responseTypeを指定している事が原因。

同期リクエストの実行時における、XMLHttpRequest responseType および withCredentials 属性の使用のサポートを削除しました。属性の使用を試みると、NS_ERROR_DOM_INVALID_ACCESS_ERR 例外が発生します。この変更は、W3C へ標準化の提案が行われました。
https://developer.mozilla.org/ja/Firefox/Releases/11

仕様上できないようなので、同期処理が必要な場合はresponseTypeへの指定を外し、responseに対して型変換など行う必要がある。
例えば json を取得したい場合、responseType 未設定だと string で返ってくるので JSON.parse する。

xhr.onreadystatechange = function () {
  if (this.readyState === 4 && this.status === 200) {
    var response = this.response;
    if (typeof response === "string") {
      resoinse = JSON.parse(response);
    }
    // ...
  }
};