Handlebars模板功能中未定义的Meteor用户对象

Tre*_*ent 3 meteor

模板上的以下简单函数通常会失败,因为user对象未定义,即使我已登录:

Template.hello.userData = function() {
  var user = Meteor.users.findOne(Meteor.userId());
  return user.emails[0].address;
};
Run Code Online (Sandbox Code Playgroud)

它很容易复制:

  • 在命令行上:
    • meteor创建测试用户
    • cd测试用户
    • meteor add accounts-password
    • meteor add accounts-ui
  • 编辑test-user.js并将'userData'代码(上面)添加到isClient块中
  • 编辑test-user.html并在'hello'模板中添加:{{loginButtons}} {{userData}}
  • 转到应用程序并创建一个帐户,该帐户会让您登录并在控制台中收到错误消息: Uncaught TypeError: Cannot read property 'emails' of undefined

阴险的是"通常"部分:它有时会成功,因此可能存在竞争条件......并且可能是依赖项被加载的顺序.

我实际上是在一个更复杂的应用程序中点击这个,试图访问我登录用户的"profile"属性(存在,我保证).它在不同的浏览器中提供略有不同的错误消息 这是Chrome中的堆栈跟踪:

Exception from Deps recompute: TypeError: Cannot read property 'profile' of undefined
    at Object.Template.workbook.owner (http://localhost:3000/client/client.js?153b3db62478692678dd9fdf9f1a9dd0b6b6a76e:130:21)
    at apply (http://localhost:3000/packages/handlebars.js?c2b75d49875b4cfcc7544447aad117fd81fccf3b:276:24)
    at invoke (http://localhost:3000/packages/handlebars.js?c2b75d49875b4cfcc7544447aad117fd81fccf3b:301:12)
    at http://localhost:3000/packages/handlebars.js?c2b75d49875b4cfcc7544447aad117fd81fccf3b:365:30
    at Object.Spark.labelBranch (http://localhost:3000/packages/spark.js?3a050592ceb34d6c585c70f1df11e353610be0ab:1171:14)
    at branch (http://localhost:3000/packages/handlebars.js?c2b75d49875b4cfcc7544447aad117fd81fccf3b:355:20)
    at http://localhost:3000/packages/handlebars.js?c2b75d49875b4cfcc7544447aad117fd81fccf3b:364:18
    at Array.forEach (native)
    at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?13ab483e8a3c795d9991577e65e811cd0b827997:130:11)
    at template (http://localhost:3000/packages/handlebars.js?c2b75d49875b4cfcc7544447aad117fd81fccf3b:358:7) debug.js:41
Exception from Deps recompute: Error: Can't create second landmark in same branch
    at Object.Spark.createLandmark (http://localhost:3000/packages/spark.js?3a050592ceb34d6c585c70f1df11e353610be0ab:1226:13)
    ...<snip>...

最后一个错误是关于Can't create second landmark in same branch通过其他帖子发送我的所有与循环有关,但这只是一个简单的集合访问.forEach堆栈跟踪中有一些调用,所以我尝试像Meteor问题281那样的解决方案,但无济于事.

非常感谢Meteor公约的提示和解释.谢谢.

小智 5

我遇到了同样的问题.

return user && user.emails[0].address;
Run Code Online (Sandbox Code Playgroud)

首先检查用户是否未定义(用户&& ...)似乎已经完成了.