Why am I getting "potentially invalid reference access to a class field via this in a nested function" error
The warning is telling you that using this
in JavaScript frequently has confusing implications, specifically when used inside a function nested inside another function. this
stops referring to the class, and instead refers to the scope of your nested function.
In your case, this probably is a legitimate problem (I think) because you have your class, Wall
, which has a method previewImages()
and a property files
. Within that function, you have instantiated a new function, readAndPreview()
, inside which you specify this.previewImages
as a function callback to the addEventListener
function.
They're saying you're potentially using this.previewImages
incorrectly, because you're writing functions in traditional JavaScript syntax, function foo() { ... }
, where this
keeps being redefined in each child function call. In your case, I believe that this
is referring to the context of readAndPreview()
, and hence cannot access the method this.previewImages()
since this
doesn't refer to your parent class, Wall
.
People used to do things like, make a var that = this;
on the parent class, and you'd know that that
always meant the parent class.
But now, with ES6 lambda functions using the "fat arrow" syntax () => { }
you can access this
and know it's referring to the parent scope.
I believe you can refactor your class to change previewImages() {
into previewImages = () => {
and know that this
will refer to the class. You'll have to do the same with function readAndPreview() {
. Change it to const readAndPreview = () => {
. If you're setting it to a variable, though, I think you'll have to move it above the place you call it, though. e.g. above
if (this.files) { [].forEach().call(this.files, readAndPreview());}
I faced this error in Angular 8.I used the Arrow function instead of regular functions to solve.
In your case.
readAndPreview = () => { ... }
This might solve your problem.