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

React中如何将函数参数传递到API调用的.then回调中?

解决API回调中参数未定义的问题

你遇到的actionTypeId is not defined错误,核心原因是.then的普通function回调会创建独立作用域,无法直接访问外部函数的referralData.actionTypeId。以下是几种简单的解决方法:

方法1:使用箭头函数(推荐)

箭头函数不会绑定自身作用域,会继承外部函数的作用域,因此可以直接访问referralData:

function createReferral(referralData: { actionTypeId: number }) {
  referralAxios.post(`/api/ReferralMasters`, {
    appTypeID: referralData.actionTypeId, // 注意:原代码此处写的是appTypeId,疑似笔误,建议修正为actionTypeId
  }).then((response) => {
    console.log(referralData.actionTypeId);
  });
}

方法2:提前提取变量到当前作用域

把需要用到的变量先提取到外部函数的作用域中,回调函数就能直接访问:

function createReferral(referralData: { actionTypeId: number }) {
  const targetId = referralData.actionTypeId;
  referralAxios.post(`/api/ReferralMasters`, {
    appTypeID: targetId,
  }).then(function (response) {
    console.log(targetId);
  });
}

方法3:通过bind绑定上下文

给回调函数绑定包含目标变量的上下文,不过这种方式相对繁琐,一般不推荐:

function createReferral(referralData: { actionTypeId: number }) {
  referralAxios.post(`/api/ReferralMasters`, {
    appTypeID: referralData.actionTypeId,
  }).then(function (response) {
    console.log(this.actionTypeId);
  }.bind({ actionTypeId: referralData.actionTypeId }));
}

另外注意:原代码中POST请求的参数里写的是appTypeId,但函数参数定义的是actionTypeId,这大概率是笔误,建议同步修正,避免API请求参数错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:07:21