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

使用react-google-apps-script时Session与PropertiesService为何未定义?

问题原因及解决方案

核心原因

你遇到的Session、PropertiesService未定义问题,主要来自两个方面:

  1. OAuth权限缺失:这两个API需要特定的授权范围,若appscript.json未配置对应权限,会导致调用时出现对象未定义或权限报错。
  2. 函数暴露/执行上下文问题:react-google-apps-script的打包机制要求服务端函数必须正确导出,才能被识别为GAS可调用函数,否则可能在错误的上下文执行。

具体解决步骤

1. 补充OAuth权限到appscript.json

打开appscript.json,在oauthScopes数组中添加以下必要权限:

"oauthScopes": [
  "https://www.googleapis.com/auth/spreadsheets",
  "https://www.googleapis.com/auth/userinfo.email", // 用于Session.getActiveUser()
  "https://www.googleapis.com/auth/script.properties", // 用于PropertiesService
  "https://www.googleapis.com/auth/script.external_request"
]

2. 确保服务端函数正确导出

在server目录下的文件中,按ES模块语法导出服务端函数,示例:

// server/userFunctions.js
export function getActiveUserEmail() {
  return Session.getActiveUser().getEmail();
}

export function getAppProperty(key) {
  return PropertiesService.getScriptProperties().getProperty(key);
}

3. 客户端正确调用服务端函数

客户端通过import引入服务端函数后,需以异步方式调用(react-google-apps-script会自动封装为google.script.run调用):

// client/ProfileComponent.jsx
import { getActiveUserEmail } from '../server/userFunctions';

const loadUserEmail = async () => {
  try {
    const email = await getActiveUserEmail();
    console.log('当前用户邮箱:', email);
  } catch (error) {
    console.error('获取邮箱失败:', error);
  }
};

4. 重新部署并授权

修改权限后,重新部署你的脚本,在弹出的授权窗口中确认授予所有请求的权限。

额外注意事项

  • 确保appscript.json中的runtimeVersion设置为"V8",ES模块语法仅在V8运行时支持。
  • 参考Enushi提供的示例代码,核对项目结构(server/client目录划分、配置文件位置)是否符合react-google-apps-script的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:56:30