GLTFLoader: Reference error when loading model

I am loading the model in angular using GTLF loader.

code is:

 initObjectLoader(): void {
    // Init the object loader
    this.loader =  new GLTFLoader();

    this.loader.load(
      this.modelPath,
      function (gltf: GLTF) {

        // start
        // KEEP
        console.log('SCNEE IS ', gltf.scene);
        this.theModel = gltf.scene;         // <--- error
        
        this.theModel.traverse((o) => {
          if (o.isMesh) {
            o.castShadow = true;
            o.receiveShadow = true;
          }
        });
        // Set the models initial scale
        this.theModel.scale.set(1, 1, 1);
      

        console.log("traversing to model");
        this.theModel.traverse((o) => {

          if (o.type === "Mesh") {
            console.log("-> ", o);
            o.material = this.INITIAL_MTL;

          }

        });
        console.log("traversing end");

        // Add the model to the scene
        console.log('model is', this.theModel);

        this.scene.add(this.theModel);
 
      }
      ,
      undefined,
      function (error) {
        console.error(error);
      }
    );
  }

above code is showing error :

RROR Error: Uncaught (in promise): TypeError: Cannot set properties of undefined (setting 'theModel')
TypeError: Cannot set properties of undefined (setting 'theModel')

Try to turn the onLoad() callback function into an arrow function. Doing this will not change the this reference and potentially fix your issue.