InvalidTypeException: The properties accessed are undefined

Working with Angular 12 and encountering an error when trying to invoke a method within another method. Here is a simplified representation of my situation (in TypeScript, specifically for Angular:

export class SomeClass {

testvariable

onTaskCompleted(results) {
if (!results) {
    return;
} else {
    //This line works fine
    console.log(results);
    //This line triggers an error
    this.drawSomething(results)
    //Actually, any reference to something outside of this function generates an error
    this.testvariable = results
}
}

//The unique aspect of OnTaskCompleted is that it also serves as a callback handler for a third-party library, which causes the error.
//It is invoked in another function like so. It produces the correct result in onTaskCompleted but breaks whenever I attempt something similar to above.
this.something.onResults(this.onResults);

drawSomething(results) {
if (!results) {
    return;
} else {
    //perform some tasks
}
}
}

Upon running this code, I encounter a TypeError: Cannot read properties of undefined. When I include the doSomethingElse function within any other functions defined in my class, everything works as expected without any issues. The only significant observation is that the function where I'm facing this problem, doSomething(), is utilized as a callback by an external library, which seems to be responsible for triggering the error each time I mention anything 'outside' of doSomething in that function. I would greatly appreciate any insights or thoughts on this matter.

Answer №1

The specific problem I'm facing is related to the doSomething() function, which is being used as a callback.

It seems like you're passing the function in this way:

library.callFunction(this.doSomething);

This approach presents an issue because the 'this' parameter will be set to the caller, causing it not to refer to the instance of the class anymore. Consequently, accessing a property on 'this' inside doSomething() will result in an error.

A correct way to address this would be:

library.callFunction(param => this.doSomething(param));

Arrow functions capture the correct 'this' context and exhibit the expected behavior.

Alternatively, you could explicitly bind 'this' to the function:

library.callFunction(this.doSomething.bind(this));

There are several answers provided here that explain function scoping in detail, such as .

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any @types available for browser extension objects that are interoperable?

I am in the process of developing a browser extension that would work seamlessly on Edge, Chrome, and Firefox by utilizing Typescript. After coming across an article discussing interoperable browser extensions, I stumbled upon a code snippet: window.brow ...

Error encountered when extending Typography variant in TypeScript with Material UI v5: "No overload matches this call"

Currently, I am in the process of setting up a base for an application using Material UI v5 and TypeScript. My goal is to enhance the Material UI theme by adding some custom properties alongside the default ones already available. The configuration in my ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

Utilizing a package from your local computer

Due to my current circumstances, I am unable to utilize the npm publish command to release a package on the internet and subsequently use npm install. I also have no intention of publishing it on a remote server like nexus. Is there a method available to ...

Is error propagation from nested Promise to parent Promise not working properly in Node.js?

I'm currently working on a Node.js/TypeScript API with Express. Below is a snippet from my get method where I encountered an error in the format function. The error is caught by the promise, but it doesn't propagate to the parent promise after th ...

Declare that a method alters a value with state

Here's a more streamlined version of my code. Check out my custom hook below: export const useStep = () => { const [step, setStep] = useState<Steps>("sending"); const changeStep = (newStep: Steps) => setStep(newStep); return { ste ...

Transform an Array into a String using Angular

Is there a more efficient way to extract all the state names from the array (testArray) and convert them to strings ('Arizona','Alaska','Florida','Hawaii','Gujarat','Goa','Punjab'...)? ...

Having trouble resolving modules after generating tsconfig.json?

I recently added a tsx component to my next.js 13 project following the documentation. After creating the required tsconfig.json file, I encountered module not found errors when running npm run dev: $ npm run dev > [email protected] dev > n ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

Angular 5: Transforming and Concealing CSS Class Names

Can CSS selectors be renamed or obfuscated in an Angular CLI project? Many top websites like Google and Facebook use randomized CSS names for various reasons, such as preventing website scripting through targeting static class names. I would like to imple ...

Create a POST request following a GET request and handle it in Angular 2

I am in the process of developing a service that involves both GET and POST requests to be used within a component. My question is, what would be the most effective approach to achieve this? authentication.service.ts getToken() { return this.http.get ...

What is the best way to retrieve the index of the chosen option from a select element in Angular when

My Angular application includes a simple <select> element using Material design: <mat-form-field> <mat-label>Type</mat-label> <mat-select placeholder="Type" formControlName="type" name="type" id="name"> <mat-option ...

Exploring the capabilities of Typescript arrays by implementing a forEach loop in conjunction with the

I possess an array: set Array ( [0] => Array ( [name0] => J [name1] => L [name2] => C ) [1] => Array ( [data0] => 3,1,3 [data1] => 5,3 ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

Checking email format in Angular

I am currently facing an issue where users are able to successfully submit a form even after entering an invalid email format. Despite receiving an error message, the form still gets submitted. It is important to note that I am not using formGroup. Below ...

Discovering the process of reaching service members through an HTML View

Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view. For instance, let's say I have two components: User and Main. The User component retrieves a list of users from the UserServ ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

Challenges with Css Specificity

I'm having trouble adding a specific class to certain div elements. Here is the div in question: <div class="form-control drop-down-select"> </div> This is the CSS I have applied: .form-control.drop-down-select{ max-width: ...

Exploring the power of Typescript and Map in Node.js applications

I am feeling a little perplexed about implementing Map in my nodejs project. In order to utilize Map, I need to change the compile target to ES6. However, doing so results in outputted js files that contain ES6 imports which causes issues with node. Is t ...