Loading

ReferenceError when running an LWC component

Publiseringsdato: Oct 24, 2022
Beskrivelse
In the 240.8 patch release, customers may encounter a new runtime error. It occurs for code written in the following pattern:
// Invalid: Create an instance of a class...
const foo = new Foo();

// ... that is defined after it is instantiated.
class Foo {
  // your code here
}

The above code, as well as any code that uses this pattern, is invalid JavaScript. In 240.8, it will result in one of the following runtime errors:
  • ReferenceError: Foo is not defined
  • ReferenceError: Cannot access 'Foo' before initialization
As explained in the MDN documentation on JavaScript classes: "An important difference between function declarations and class declarations is that while functions can be called in code that appears before they are defined, classes must be defined before they can be constructed."

In previous versions of the Salesforce platform, a customer using this pattern in their code may not have experienced any issues. The change in behavior and introduction of this ReferenceError in 240.8 are because:
  • In previous versions of the LWC compiler, a quirk in its internals caused the customer's invalid code to be transformed into valid code (i.e. it compiled and executed, even though the original component code is invalid).
  • In order to address a potential security issue, we made configuration changes to the LWC compiler.
  • These configuration changes eliminated the quirk that originally papered over the invalid JavaScript.
  • The invalid JavaScript now cannot execute because it is invalid and we are no longer fixing it.
The ReferenceError may be obfuscated by another error. For example, if the invalid pattern is used inside an ES6 JavaScript module, the customer may also be presented with an import error. For example, if the instance were to be exported:
// Invalid: Create an instance of a class...
const foo = new Foo();

// ... that is defined after it is instantiated...
class Foo {
  someMethod() {
    /* customer code here */
  }
}

// ... and the instance is exported using ES6 module syntax.
export default foo;
Elsewhere in the application, that instance might be depended on like so:
import foo from 'the-above-example';

// An error might appear here:
foo.someMethod();

When someMethod is invoked, the customer would be presented with: foo.default.someMethod is not a function.

This error would be displayed in addition to the ReferenceError.
Løsning
To fix invalid code, ensure that any class is defined before it is referenced (i.e. move new Foo after class Foo). A corrected version of the original example is:
// Define the class you want to use...
class Foo {
  // customer code here
}

// ... and only then create an instance.
const foo = new Foo();
Knowledge-artikkelnummer

000393510

 
Laster
Salesforce Help | Article