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

React函数参数undefined问题:表单值传递至fetch请求异常排查

问题原因与解决方案

你遇到的问题是函数参数定义和调用方式不匹配,和异步无关,纯粹是语法层面的错误:

问题细节

addRequests函数定义时使用了对象解构参数,它期望接收一个包含restaurant、partySize、time、expiration_date属性的对象:

const addRequests = async ({restaurant,partySize,time,expiration_date}) => { ... }

但你调用函数时,传递的是四个独立的变量:

addRequests(restaurant,partySize,time,expiration_date)

此时函数会把第一个参数(restaurant对象)当成要解构的目标对象,试图从里面提取partySize等属性——但restaurant对象本身没有这些属性,所以函数内部这些变量会变成undefined。

两种解决方法

方法一:修改调用方式,传递对象参数

保持函数定义不变,把按钮的点击事件改成传递一个包含所有属性的对象:

<button onClick={() => addRequests({restaurant, partySize, time, expiration_date})}> Make Request </button>

方法二:修改函数定义,接收独立参数

保持调用方式不变,把函数的参数改成四个独立变量:

const addRequests = async (restaurant, partySize, time, expiration_date) => {
  console.log(partySize)
  console.log(time)
  console.log(expiration_date)
  let item={"restaurant":restaurant.restaurant_name,"party_size":partySize,"time": time,"expiration_date":expiration_date}
  let result = await fetch("api thingy", {
      method: 'POST',
      headers:{
          "Content-Type":"application/json",
          "Accept":'application/json'
      },
      body:JSON.stringify(item)
  })
  result = await result.json();
};

补充说明

你之前用console.log(partySize)能拿到正确值,是因为直接访问了组件的state变量,和函数参数传递的错误无关。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:15:18