You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法使用fetch API函数中设置的History.state属性?

问题描述

我写了一个用fetch()调用API的函数,打算把返回的JSON通过history.pushState(json)存入History.state,但之后调用另一个函数打印history.state时输出的是null。

我尝试的代码如下:

function1();
function2();

function function1() {
  const request = new Request('https://reqres.in/api/users?page=2');
  fetch(request)
  .then(response => response.json())
  .then(
    json => 
    {
      history.pushState(json,'','');
      console.log(history.state)
    }
  );
}

function function2() {
  console.log(history.state);
}

我甚至用while循环等待history.state不为null(以为是执行顺序的问题),但没效果。实际输出结果是:

null
// [object Object] 
{
  "page": 2,
  "per_page": 6,
  "total": 12,
...

原因分析

这是异步执行顺序导致的问题:fetch()是异步操作,它的回调(.then里的代码)会在浏览器主线程空闲时才执行;而function2()是同步执行的——在function1()调用后立刻就运行了,此时API请求还未完成,history.pushState根本没执行过,所以history.state还是默认的null。

用while循环等待完全无效,因为while循环会阻塞主线程,导致浏览器根本没时间处理fetch的异步回调,最终陷入死循环。

解决方案

要确保function2()在history.pushState执行之后再调用,有几种可靠方式:

方式1:在fetch回调内直接调用function2

把function2()放到fetch的最后一个.then里,保证状态更新后再执行:

function1();

function function1() {
  const request = new Request('https://reqres.in/api/users?page=2');
  fetch(request)
  .then(response => response.json())
  .then(json => {
    history.pushState(json,'','');
    console.log(history.state);
    function2(); // 状态更新后再调用目标函数
  });
}

function function2() {
  console.log(history.state);
}

方式2:用async/await同步化异步逻辑

通过async/await让代码逻辑更直观,强制等待异步操作完成后再执行后续代码:

async function init() {
  await function1();
  function2();
}

init();

function function1() {
  const request = new Request('https://reqres.in/api/users?page=2');
  return fetch(request)
  .then(response => response.json())
  .then(json => {
    history.pushState(json,'','');
    console.log(history.state);
  });
}

function function2() {
  console.log(history.state);
}

方式3:监听状态变化事件(适用于自动触发场景)

如果需要在history.state变化时自动执行逻辑,可以监听popstate事件(注意:pushState不会自动触发该事件,需手动触发):

function1();

window.addEventListener('popstate', () => {
  console.log(history.state);
  function2();
});

function function1() {
  const request = new Request('https://reqres.in/api/users?page=2');
  fetch(request)
  .then(response => response.json())
  .then(json => {
    history.pushState(json,'','');
    console.log(history.state);
    // 手动触发popstate事件,触发监听逻辑
    window.dispatchEvent(new PopStateEvent('popstate'));
  });
}

function function2() {
  console.log(history.state);
}

内容的提问来源于stack exchange,提问作者phat-le248

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:40:45