主题调用 next 导致一个奇怪的错误 [英] Subject call to next causing a strange error
问题描述
这会导致以下错误:Cannot read property 'length' of undefined
const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(msg$.next);
但是,如果我将 msg$.next 包装在一个函数中,那么它可以正常工作而不会出现任何错误.
If, however, I wrap msg$.next in a function, then it works without any errors.
- 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 问题.
They're all just wrapper functions that seemingly do nothing but call the next function. What's going on here? Seems like there's a JavaScript gotcha I'm not aware of at work here.
推荐答案
为后人接受答案
我认为这个问题归结为这个"的价值是什么?将函数作为参数传递时?".您可能会在这里找到一些答案如何访问正确的 this回调?.
I think this question comes down to "What's the value of "this" when passing a function as parameter?". You might find some answers here How to access the correct this inside a callback?.
this
在您的第一个示例中具有错误的值.如果你把一个 console.log(this)
放在 nextMsg
里面,你会看到它是一个 SafeSubscriber
,它缺少属性 observers.length
被访问.rxjs6 中的 Subject#next
函数依赖于这是一个带有 observers.length
属性的 Subject
属性
this
has the wrong value in your first example. If you put a console.log(this)
inside nextMsg
you will see that it's a SafeSubscriber
which lacks the property observers.length
that is accessed. The Subject#next
function in rxjs6 relies on this to be a Subject
with an observers.length
property
是的,当然.看起来很傻,我没有注意到.msg$.next.bind(msg$)
有效.
Yup, of course. Seems silly that I didn't notice. msg$.next.bind(msg$)
works.
obj.func
没有 obj
作为上下文,而 obj.func()
有.
obj.func
doesn't have obj
as a context, whereas obj.func()
does.
这篇关于主题调用 next 导致一个奇怪的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!