Mobx : changing (observed) observable values without using an action is not allowed (asynchronus handler) - mobx

we know all this problem, and know how to solve it.
But I have an stranger Error in this context where I could use a good hint:
this.getData(id)
.then((response) => {
this.root.basic.selected.num = response.data.number; // number
this.root.basic.selected.date = response.data.date; // Date
this.root.basic.selected.text = response.data.text; // String. <- There is the error
}
})
The selected Object is bound by the "makeAutoObserveable()" Nothing special here. But a lot of code to push it all here.
Why this error happens only on the .text setter not on the others?
Is this a possible known behavior?
I solved it with "runInAction()" but I would like to understand the reason.
Kind Regards
Gregor

Related

trace() error "can only be used inside a tracked computed value or a Reaction" when used inside computed

I've used MobX for a few years now, and love it, but sometimes my trace calls are not functioning, and I don't understand why not. There must be some fundamental thing that I've completely misunderstood, but most likely have been lucky enough to get through anyway. Here's an example of using trace() where I'm getting an error:
import { computed, observable, trace } from "mobx";
class Stat {
#observable baseValue = 1;
#computed get value() {
trace();
return this.baseValue;
}
}
const strength = new Stat();
strength.baseValue = strength.baseValue + 1;
The expected output, in my mind, is that trace reacts to the change in "baseValue" and logs the change. Instead, I'm getting the following error:
Error: [MobX] 'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly
"Inside a tracked computed value" is, to my understanding, exactly what I'm doing. Or..?
Full sandbox: https://codesandbox.io/s/mobx-trace-trouble-ki2qj?file=/index.ts:0-312
As far as I understand this phrase
inside a tracked computed value or a Reaction.
you need to access computed value inside reactive context, like inside observer or reaction or autorun. Otherwise trace just don't have information about what is going on because your computed value is untracked at that moment by any observer.
So this will work:
const MyComponent = observer(() => {
return <div>{strength.value}</name>
})
or this
autorun(() => {
console.log(strength.value);
});

How to assign the value inside the if condition in vue?

I don't know if vue recognize the syntax below:
if(var error = errors.description){
location.href = "/redirect?topic="+error;
}
The code above returns a compilation error:
ERROR in ./resources/js/forms/Signup.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/forms/Signup.vue?vue&type=script&lang=js&)
Someone knows how to assign a variable inside the if else condition?
This is rather a JavaScript syntax issue than Vue. While I highly recommend not assigning within a conditional, you can do so only by either declaring the variable earlier or not explicitly declaring it at all, i.e. by removing the var above.
Here's an example with your above code:
if(error = errors.description){
location.href = "/redirect?topic="+error;
}
To be clear, it is highly recommended not to do the above, or at the very least declare var error earlier so that you don't accidentally modify a global variable, like so:
let error;
if(error = errors.description){
location.href = "/redirect?topic="+error;
}
Of course the most explicit and safe solution to avoid confusion about the assignment is to simply do it earlier:
let error = errors.description;
if (error) {
location.href = "/redirect?topic="+error;
}
There has been some discussion about whether assignment within conditionals is good practice. However, on a completely separate note it is widely agreed that assigning variables that haven't been declared with var, let, or const is dangerous as you could accidentally modify variables of higher scope.

Jest spyOn vs mock - both defined and undefined errors

Just upgraded to jsdom-fourteen in my jest configuration. It's working wonderfully, but a single test is failing.
test('Do the thing', () => {
window.location.assign = jest.fn();
});
I inherited this code. It looks like a simple enough jest mock. It complains that it cannot assign the read-only property assign and that makes sense, I assume this is jsdom functionality that was added.
However... I can't do a jest.spyOn either, which seems to be what is suggested. I've not used spyOn before.
jest.spyOn(window.location.assign);
But this gives me an undefined property error:
Cannot spy the undefined property because it is not a function; undefined given instead
The line before this, I added a log just to check. It is definitely a function:
console.log(window.location.assign);
=> [Function: assign]
I'm not sure how these two errors can even coexist - both defined and undefined?
Due to how JavaScript works, it would be impossible to write spyOn function the way that allowed it to work like spyOn(window.location.assign). Inside spyOn, it's possible to retrieve window.location.assign function that was provided as an argument but not window.location object and assign method name to do window.location.assign = jest.fn().
The signature of spyOn is:
jest.spyOn(object, methodName)
It should be:
jest.spyOn(window.location, 'assign');
This may be unworkable as well because window.location.assign is read-only in later JSDOM versions, which is used by Jest to emulate DOM in Node.js. The error confirms that this is the issue.
It may be possible to mock read-only property manually:
const origAssign = Object.getOwnPropertyDescriptor(window.location, 'assign');
beforeEach(() => {
Object.defineProperty(window.location, 'assign', { value: jest.fn() })
});
afterEach(() => {
Object.defineProperty(window.location, 'assign', origAssign)
});
This wouldn't work with real DOM because built-ins may be read-only and non-configurable. This is the issue in Chrome. For testability reasons it may be beneficial to use location.href instead of location.assign.
Eventually worked through some things and found this:
delete global.window.location;
window.location = { assign : jest.fn()};
As it appears later iterations of jsdom lock the location object down further and further until it's completely not modifiable, #Estus' answer will only work in lower versions of jsdom/jest.

Knockout components using OOP and inheritance

I was hoping I could get some input on how to use Knockout components in an object-oriented fashion using Object.create (or equivalent). I'm also using Postbox and Lodash, in case some of my code seems confusing. I've currently built a bunch of components and would like to refactor them to reduce code redundancy. My components, so far, are just UI elements. I have custom input boxes and such. My initial approach was as follows, with some discretion taken to simplify the code and not get me fired :)
// Component.js
function Component() {
var self = this
self.value = ko.observable()
self.initial = ko.observable()
...
self.value.subscribeTo('revert', function() {
console.log('value reverted')
self.value(self.initial())
}
}
module.exports = Component
// InputBox.js
var Component = require('./Component')
var _ = require('lodash')
function InputBox(params) {
var self = this
_.merge(self, params) // quick way to attach passed in params to 'self'
...
}
InputBox.prototype = Object.create(new Component)
ko.components.register('input-box', InputBox)
Now this kind of works, but the issue I'm having is that when I use the InputBox in my HTML, I pass in the current value as a parameter (and it's also an observable because the value is retrieved from the server and passed down through several parent components before getting to the InputBox component). Then Lodash merges the params object with self, which already has a value observable, so that gets overwritten, as expected. The interesting part for me is that when I use postbox to broadcast the 'revert' event, the console.log fires, so the event subscription is still there, but the value doesn't revert. When I do this in the revert callback, console.log(self.value(), self.initial()), I get undefined. So somehow, passing in the value observable as a parameter to the InputBox viewmodel causes something to go haywire. When the page initially loads, the input box has the value retrieved from the server, so the value observable isn't completely broken, but changing the input field and then hitting cancel to revert it doesn't revert it.
I don't know if this makes much sense, but if it does and someone can help, I'd really appreciate it! And if I can provide more information, please let me know. Thanks!
JavaScript does not do classical inheritance like C++ and such. Prototypes are not superclasses. In particular, properties of prototypes are more like static class properties than instance properties: they are shared by all instances. It is usual in JS to have prototypes that only contain methods.
There are some libraries that overlay a classical-inheritance structure onto JavaScript. They usually use "extends" to create subclasses. I don't use them, so I can't recommmend any in particular, but you might look at Coffeescript if you like the classical-inheritance pattern.
I often hear "favor composition over inheritance," but I generally see a lot of emphasis on inheritance. As an alternative, consider Douglas Crockford's "class-free object-oriented programming", which does away with inheritance entirely.
For what you're trying to do here, you probably want to have InputBox initialize itself with Component, something like:
function InputBox(params) {
var self = this
Component.bind(self)(); // super()
_.merge(self, params) // quick way to attach passed in params to 'self'
...
}
The new, merged, value will not have the subscription from Component, because the subscription is particular to Component's instance of the observable, which will have been overwritten.
To everyone who responded, thank you very much! I've found a solution that works better for me and will share it here in case anyone is interested.
// Component.js (only relevant parts shown)
function Component(params) {
var self = this
_.merge(self, params)
self.value.subscribeTo('some event', function() {
// do some processing
return <new value for self.value>
}
module.exports = Component
// InputBox.js
var Component = require('./component')
function InputBox(params) {
var self = this
Component.call(self, params)
}
By taking this approach, I avoid the headache of using prototypes and worrying about the prototype chain since everything Component does is done directly to the "inheriting" class. Hope this helps someone else!

How to register component interface in wxwebconnect?

I'm doing an experiment with wxWebConnect test application, incorporating the xpcom tutorial at "http://nerdlife.net/building-a-c-xpcom-component-in-windows/"
I adapt MyComponent class as necessary to compile together with testapp.exe (not as separate dll), and on MyApp::OnInit I have the following lines:
ns_smartptr<nsIComponentRegistrar> comp_reg;
res = NS_GetComponentRegistrar(&comp_reg.p);
if (NS_FAILED(res))
return false;
ns_smartptr<nsIFactory> prompt_factory;
CreateMyComponentFactory(&prompt_factory.p);
nsCID prompt_cid = MYCOMPONENT_CID;
res = comp_reg->RegisterFactory(prompt_cid,
"MyComponent",
"#mozilla.org/mycomp;1",
prompt_factory);
Those lines are copied from GeckoEngine::Init(), using the same mechanism to register PromptService, etc. The code compiles well and testapp.exe is running as expected.
I put javascript test as below :
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
const cid = "#mozilla.org/mycomp;1";
obj = Components.classes[cid].createInstance();
alert(typeof obj);
// bind the instance we just created to our interface
alert(Components.interfaces.nsIMyComponent);
obj = obj.QueryInterface(Components.interfaces.nsIMyComponent);
} catch (err) {
alert(err);
return;
}
and get the following exception:
Could not convert JavaScript argument arg 0 [nsISupport.QueryInterface]
The first alert says "object", so the line
Components.classes[cid].createInstance()
is returning the created instance.
The second alert says "undefined", so the interface nsIMyComponent is not recognized by XULRunner.
How to dynamically registering nsIMyComponent interface in wxWebConnect environment ?
Thx
I'm not sure what is happening here. The first thing I would check is that your component is scriptable (I assume it is, since the demo you copy from is). The next thing I would check is whether you can instantiate other, standard XULRunner components and get their interface (try something like "alert('Components.interfaces.nsIFile');" - at least in my version of wxWebConnect this shows an alert box with string "nsIFile".
Also, I think it would be worth checking the Error Console to make sure there are no errors or warnings reported. A magic string to do that (in Javascript) is:
window.open('chrome://global/content/console.xul', '', 'chrome,dialog=no,toolbar,resizable');