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

执行Twilio函数时出现'Cannot read properties of undefined (reading 'phoneNumbers')'错误求助

解决Twilio Serverless Function中Lookup v2 API的TypeError问题

问题重现

在Twilio控制台「Functions and Assets」中部署的Function代码如下(参照Lookup v2 API官方示例):

exports.handler = function (context, event, callback) {
    const client = context.getTwilioClient();
    client.lookups.v2.phoneNumbers('+14159929960')
      .fetch()
      .then(phone_number => console.log(phone_number.phoneNumber));
};

已确认API凭据配置正确、Function设为公开访问,但执行时抛出以下错误:

{"message":"Cannot read properties of undefined (reading 'phoneNumbers')","name":"TypeError","stack":"TypeError: Cannot read properties of undefined (reading 'phoneNumbers')\n at Object.exports.handler (/var/task/handlers/ZNa5464231185aba5ad490f6de6e20b5d0.js:7:21)\n at Object.exports.handler (/var/task/node_modules/runtime-handler/index.js:339:10)\n at Runtime.exports.handler (/var/task/runtime-handler.js:17:17)\n at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1..."}

问题原因

Twilio Serverless环境默认搭载的Twilio SDK版本可能低于v4.x,而Lookup v2 API是在SDK v4版本中新增的特性。旧版SDK不存在lookups.v2层级,因此调用时触发undefined错误。

解决方案

1. 指定Twilio SDK v4.x版本

  • 本地开发项目:在项目根目录的package.json中添加明确的依赖声明:
{
  "dependencies": {
    "twilio": "^4.0.0"
  }
}
  • 控制台直接编辑:进入Function的「Settings」,开启「Enable npm support」,在「Dependencies」列表中添加twilio@^4.0.0。

2. 完善代码的回调逻辑

原代码未调用callback函数,会导致Function执行超时。需在Promise的成功和失败分支中分别调用callback返回结果:

exports.handler = function (context, event, callback) {
    const client = context.getTwilioClient();
    client.lookups.v2.phoneNumbers('+14159929960')
      .fetch()
      .then(phone_number => {
          console.log(phone_number.phoneNumber);
          callback(null, phone_number); // 返回成功数据
      })
      .catch(error => {
          console.error(error);
          callback(error); // 返回错误信息
      });
};

3. 重新部署Function

保存所有修改后,重新部署Serverless服务,确保新的SDK版本被安装并生效。

验证

部署完成后调用Function的公开URL,若成功则返回电话号码的Lookup详情;若仍有错误,可在Twilio控制台的「Logs」标签页查看完整错误日志排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:05:22