由于“无法读取未定义的 属性 'add'”错误,函数不断崩溃

Function keeps crashing due to 'Cannot read property 'add' of undefined' error

当我 运行 这个 Firebase 函数时,我一直收到这个错误:

TypeError: Cannot read property 'add' of undefined
    at visaCountry (/srv/index.js:51:11)
    at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/srv/index.js:105:40)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at /worker/worker.js:783:7
    at /worker/worker.js:766:11
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)

agent 变量在其设置的范围内工作,但 returns undefinedvisaCountry 函数内工作。有谁知道为什么会这样?

函数

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

var serviceAccount = require("./config/sdkjfhdsjkhfjdsf.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://sdfdsfjshdfjds.firebaseio.com"
});

var db = admin.firestore();

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  console.log('Agent = '+ agent);

  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  // An action is a string used to identify what needs to be done in fulfillment
  let action = agent.action;
  console.log('Actions = '+ JSON.stringify(action));

  // Parameters are any entites that Dialogflow has extracted from the request.
  const parameters = agent.parameters; // https://dialogflow.com/docs/actions-and-parameters

  // Contexts are objects used to track and store conversation state
  const inputContexts = agent.contexts;

  function visaCountry(agent) {
    let visasRead = db.collection('requirements').doc('India').get();

    console.log('Agent = '+ agent);

    agent.add(`Here are the visas for` + visasRead.name);
  }
  let intentMap = new Map();
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('Visa Search Request', visaCountry());
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);
});

这背后的原因是因为您将函数定义为 function visaCountry(agent) { }。从技术上讲,尝试从您未传递的函数范围访问 agent 变量,这就是为什么它是 undefined.

只需将visaCountry()传递给变量agent即可。

喜欢以下内容:

intentMap.set('Visa Search Request', visaCountry(agent));

想象一下:

const agent = 'data';

run();
run(agent);

function run(agent) {
  console.log(agent);
}

希望对您有所帮助!