【问题标题】:Subject call to next causing a strange error主题调用 next 导致一个奇怪的错误
【发布时间】:2023-04-01 19:35:02
【问题描述】:

这会导致以下错误:Cannot read property 'length' of undefined

const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(msg$.next);

但是,如果我将 msg$.next 包装在一个函数中,那么它可以正常工作。

  • Lambda 函数
const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(greeting => msg$.next(greeting));
  • 匿名函数
const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(function(greeting){
  msg$.next(greeting);
});
  • 命名函数
function nextMsg(greeting){
  msg$.next(greeting);
}
const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(nextMsg);

它们都只是包装函数,看起来除了调用下一个函数之外什么都不做。这里发生了什么?似乎这里有一个我不知道的 JavaScript 陷阱。

【问题讨论】:

  • 我认为这个问题归结为“将函数作为参数传递时“this”的值是什么?”。你可能会在这里找到一些答案How to access the correct this inside a callback?this 在您的第一个示例中具有错误的值。如果您将console.log(this) 放入nextMsg 内,您将看到它是一个SafeSubscriber,它缺少可访问的observers.length 属性。 rxjs6 中的 Subject.next 函数依赖于 this 成为具有 observers.length 属性的 Subject
  • 是的,当然。似乎很愚蠢,我没有注意到。 msg$.next.bind(msg$) 有效。 a.func 没有 a 作为上下文,而 a.func() 有。如果您将您的评论作为答案,我会接受。
  • 如果您使用source$.subscribe(subjectInstance),它也可以工作。它将自动调用subject.{next,error,complete}(),具体取决于source$ 发出的内容。

标签: javascript rxjs


【解决方案1】:

为了子孙后代接受的答案


我认为这个问题归结为“将函数作为参数传递时“this”的值是什么?”。你可能会在这里找到一些答案How to access the correct this inside a callback?

this 在您的第一个示例中具有错误的值。如果您将console.log(this) 放入nextMsg 中,您将看到它是一个SafeSubscriber,它缺少可访问的observers.length 属性。 rxjs6 中的 Subject#next 函数依赖于这是一个带有 observers.length 属性的 Subject

是的,当然。似乎很愚蠢,我没有注意到。 msg$.next.bind(msg$) 有效。

obj.func 没有 obj 作为上下文,而 obj.func() 有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多