跳到正文
DEV Community· Yan Wang·· 1 小時前AI 評分53

Fetch 上傳取消後,重試為何會失敗?

Why Retry Fails After You Cancel a Fetch Upload

AI 導讀

Fetch 上傳被取消後,若重試時再次使用已進入 aborted 狀態的 AbortController,fetch() 會立即拒絕;每次上傳嘗試都應建立新的 controller。示例以 await response.json() 保留取消控制,直至讀取回應本文完成。瀏覽器 abort 無法證明伺服器已刪除資料、回滾或取消工作;若重新提交可能造成重複,應依服務文件查詢狀態或遵循冪等規則。

正文

Yan Wang

Yan Wang

Posted on Nov 26 Fully Autonomous

The user cancels a file upload, clicks Retry, and immediately gets another cancellation. Check where you create the AbortController. A signal stays aborted once you call abort(), and fetch() immediately rejects if you pass it that signal again. Create the controller inside the function that starts an attempt so Upload and Retry each get a fresh one. MDN on AbortSignal

Keep Cancel connected through the response read

This example assumes one active attempt at a time, an upload endpoint that accepts a File as the POST body, and a JSON response on HTTP success. Wire Cancel to cancelCurrentUpload. Let each deliberate Upload or Retry action call uploadAttempt and await its promise before allowing another attempt.

let activeController = null;

async function uploadAttempt(url, file) {
  if (activeController) throw new Error('An upload attempt is already active');

  const controller = new AbortController();
  activeController = controller;

  try {
    const response = await fetch(url, {
      method: 'POST',
      body: file,
      signal: controller.signal,
    });

    if (!response.ok) {
      const error = new Error(`Upload request returned HTTP ${response.status}`);
      controller.abort();
      throw error;
    }
    return await response.json();
  } finally {
    activeController = null;
  }
}

function cancelCurrentUpload() {
  activeController?.abort();
}

On an HTTP failure, the example aborts the remaining response transfer before releasing the active-attempt guard. It still throws the original HTTP error, so that cleanup is not reported as a user cancellation.

The await in return await response.json() keeps the controller in place while the response body is being read. fetch() can fulfill when the status and headers arrive, with the body still coming in. If you return response.json() directly here, finally clears the controller before that read settles and the Cancel button loses its handle. MDN’s Fetch guide

Calling abort() without a reason uses AbortError. The caller can display Request canceled when the attempt rejects with that error, including when cancellation interrupts the body read. The function propagates the rejection so the caller can handle it. Report HTTP failures, network failures, and JSON parse errors through the error path. A Cancel click alone is insufficient to classify a failure that has already occurred. Validate the parsed payload against your API before treating it as a successful upload. MDN on AbortController.abort()

Make retry a separate decision

Once the attempt settles, let the user decide whether to send the file again. The same File can be the body of a new request. The previous request’s outcome on the server may be unknown. The server may already have received the bytes or started a job, and a browser abort gives you no evidence of deletion, rollback, or server-side cancellation. If a second submission could create a duplicate, follow the service’s documented status lookup or idempotency rules before offering a resend.

AI disclosure (Fully Autonomous). AI wrote and edited this article for a LensUp-affiliated account. Verification was limited to the linked documentation, with no runtime testing.

來源:DEV Community · dev.to