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

React Axios同提交处理函数内先后调用Get和Post无法获取返回值问题

问题原因

  • 这是JavaScript异步执行顺序的典型问题:axios.get是异步网络请求,不会阻塞后续代码执行。你写在then回调外的打印日志、构造FormData、发起POST请求的代码,会在GET请求还没拿到返回结果时就提前执行,此时this.state.creator还没有被赋值,自然返回null。
  • 额外补充:直接修改this.state不符合React规范,修改state必须调用this.setState方法,不过当前场景是临时取数赋值给表单,也可以不用修改state,直接使用接口返回的用户数据即可。

修复方案

方案1:将POST请求逻辑移入GET请求的then回调中

handleSubmit = (e) => {
  e.preventDefault();
  axios.get('http://127.0.0.1:8000/core/current_user/', {
    headers: {
      Authorization: `JWT ${localStorage.getItem('token')}`,
    }
  }).then((user) => {
    // 拿到用户信息后再执行后续POST逻辑
    const creator = user.data;
    console.log(creator);
    let form_data = new FormData();
    form_data.append('creator', creator);
    form_data.append('file', this.state.file);
    form_data.append('title', this.state.title);
    form_data.append('description', this.state.description);
    return axios.post('http://localhost:8000/core/posts/', form_data, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `JWT ${localStorage.getItem('token')}`,
      }
    })
  }).then(res => {
    console.log(res.data);
  }).catch(err => console.log(err))
};

方案2:用async/await语法简化异步逻辑,可读性更高

handleSubmit = async (e) => {
  e.preventDefault();
  try {
    // 等待GET请求返回用户信息后再向下执行
    const userRes = await axios.get('http://127.0.0.1:8000/core/current_user/', {
      headers: {
        Authorization: `JWT ${localStorage.getItem('token')}`,
      }
    });
    const creator = userRes.data;
    console.log(creator);
    let form_data = new FormData();
    form_data.append('creator', creator);
    form_data.append('file', this.state.file);
    form_data.append('title', this.state.title);
    form_data.append('description', this.state.description);
    const postRes = await axios.post('http://localhost:8000/core/posts/', form_data, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `JWT ${localStorage.getItem('token')}`,
      }
    });
    console.log(postRes.data);
  } catch (err) {
    console.log(err);
  }
};

内容的提问来源于stack exchange,提问作者Tochy Egeonu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:45:04