Skip to content

Commit 9805f70

Browse files
committed
Fix no-direct-mutation-state detection with nested components (fixes #1382)
1 parent 6af4bca commit 9805f70

File tree

2 files changed

+30
-11
lines changed

2 files changed

+30
-11
lines changed

lib/rules/no-direct-mutation-state.js

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,23 +48,25 @@ module.exports = {
4848
// --------------------------------------------------------------------------
4949
// Public
5050
// --------------------------------------------------------------------------
51-
let inConstructor = false;
52-
let inCallExpression = false;
53-
5451
return {
5552
MethodDefinition(node) {
5653
if (node.kind === 'constructor') {
57-
inConstructor = true;
54+
components.set(node, {
55+
inConstructor: true
56+
});
5857
}
5958
},
6059

61-
CallExpression: function() {
62-
inCallExpression = true;
60+
CallExpression: function(node) {
61+
components.set(node, {
62+
inCallExpression: true
63+
});
6364
},
6465

6566
AssignmentExpression(node) {
6667
let item;
67-
if ((inConstructor && !inCallExpression) || !node.left || !node.left.object) {
68+
const component = components.get(utils.getParentComponent());
69+
if (!component || (component.inConstructor && !component.inCallExpression) || !node.left || !node.left.object) {
6870
return;
6971
}
7072
item = node.left;
@@ -75,7 +77,6 @@ module.exports = {
7577
item.object.type === 'ThisExpression' &&
7678
item.property.name === 'state'
7779
) {
78-
const component = components.get(utils.getParentComponent());
7980
const mutations = (component && component.mutations) || [];
8081
mutations.push(node.left.object);
8182
components.set(node, {
@@ -85,13 +86,17 @@ module.exports = {
8586
}
8687
},
8788

88-
'CallExpression:exit': function() {
89-
inCallExpression = false;
89+
'CallExpression:exit': function(node) {
90+
components.set(node, {
91+
inCallExpression: false
92+
});
9093
},
9194

9295
'MethodDefinition:exit': function (node) {
9396
if (node.kind === 'constructor') {
94-
inConstructor = false;
97+
components.set(node, {
98+
inConstructor: false
99+
});
95100
}
96101
},
97102

tests/lib/rules/no-direct-mutation-state.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,20 @@ ruleTester.run('no-direct-mutation-state', rule, {
6969
' }',
7070
'}'
7171
].join('\n')
72+
}, {
73+
code: `
74+
class OneComponent extends Component {
75+
constructor() {
76+
super();
77+
class AnotherComponent extends Component {
78+
constructor() {
79+
super();
80+
}
81+
}
82+
this.state = {};
83+
}
84+
}
85+
`
7286
}],
7387

7488
invalid: [{

0 commit comments

Comments
 (0)