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

Google Script报错:TypeError无法解构undefined的e的namedValues

排查Google Script表单提交函数_onFormSubmit的TypeError错误

核心错误根源:事件对象判断逻辑完全写反

代码第一行的判断逻辑彻底错误:

  • 表单自动触发时,e是包含事件数据的有效对象,但原代码if (e) throw new Error(...)会直接抛出错误,阻断正常执行
  • 手动运行函数时,e才是undefined,此时判断不触发,执行到解构const {namedValues, range} = e时,就会抛出TypeError: Cannot destructure property 'namedValues' of 'e' as it is undefined

修复方式:将判断改为检查e是否不存在,即:

if (!e) throw new Error("Auto Triggered only thru Form submit! Manual Records prevented");

其他代码问题及修复

  1. includes方法调用语法错误
    原代码formUrl.includes.CONFIG.FORM_ID.CLOCK_IN是错误写法,includes是字符串方法,需用括号传递匹配参数,正确写法:

    if (formUrl.includes(CONFIG.FORM_ID.CLOCK_IN)) { ... }
    
  2. JSDoc注释错误

    • @params应改为@param(单数形式)
    • e.namedvalues需修正为e.namedValues(Google Apps Script事件对象属性为驼峰命名,首字母大写)
  3. 无效代码清理
    注释行// const range(e)是无效语法,建议直接删除

修复后的完整代码

/**
 * @param {object} e - 表单提交事件对象
 * @param {SpreadSheetApp.Range} e.range - 提交数据对应的单元格范围
 * @param {object} e.namedValues - 表单字段名称与对应值的映射
 */

function _onFormSubmit(e) {
  if (!e) throw new Error("Auto Triggered only thru Form submit! Manual Records prevented");

  const { namedValues, range } = e;
  const sheet = range.getSheet();
  const formUrl = sheet.getFormUrl();

  if (formUrl.includes(CONFIG.FORM_ID.CLOCK_IN)) {
    handleClockIn_(e);
  } else if (formUrl.includes(CONFIG.FORM_ID.CLOCK_OUT)) {
    handleClockOut_(e);
  }
}

额外验证步骤

  • 确认已配置正确的表单提交触发器:在脚本编辑器中点击「编辑」→「当前项目的触发器」,添加表单提交触发事件,关联_onFormSubmit函数
  • 检查CONFIG.FORM_ID.CLOCK_IN和CONFIG.FORM_ID.CLOCK_OUT是否已正确定义,值为对应表单的ID字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:00:52