Skip to content

Commit

Permalink
Added error message when endless recursion is nigh
Browse files Browse the repository at this point in the history
  • Loading branch information
mweststrate committed Sep 1, 2016
1 parent 1709b48 commit 4cd8a05
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/core/computedvalue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export class ComputedValue<T> implements IObservable, IComputedValue<T>, IDeriva
protected value: T = undefined;
name: string;
isComputing: boolean = false; // to check for cycles
isRunningSetter: boolean = false; // TODO optimize, see: https://reaktor.com/blog/javascript-performance-fundamentals-make-bluebird-fast/
setter: (value: T) => void;

/**
Expand Down Expand Up @@ -129,10 +130,17 @@ export class ComputedValue<T> implements IObservable, IComputedValue<T>, IDeriva
}

public set(value: T) {
if (this.setter)
this.setter.call(this.scope, value);
if (this.setter) {
invariant(!this.isRunningSetter, `The setter of computed value '${this.name}' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`);
this.isRunningSetter = true;
try {
this.setter.call(this.scope, value);
} finally {
this.isRunningSetter = false;
}
}
else
throw new Error(`[ComputedValue '${this.name}'] It is not possible to assign a new value to a computed value.`);
invariant(false, `[ComputedValue '${this.name}'] It is not possible to assign a new value to a computed value.`);
}

private trackAndCompute(): boolean {
Expand Down
16 changes: 16 additions & 0 deletions test/observables.js
Original file line number Diff line number Diff line change
Expand Up @@ -1876,3 +1876,19 @@ test('computed getter / setter for plan objects should succeed', function (t) {

t.end();
});

test('helpful error for self referencing setter', function(t) {
var a = observable({
x: 1,
get y() {
return this.x
},
set y(v) {
this.y = v // woops...;-)
}
})

t.throws(() => a.y = 2, /The setter of computed value/)

t.end()
})

0 comments on commit 4cd8a05

Please sign in to comment.