RICHMOND, Va. — Former President Barack Obama, returning to the campaign trail on Thursday for the first time since leaving the White House, issued an unexpectedly stinging attack on the immigration-focused campaign of the Republican candidate for Virginia governor.

Seeking to lift the candidacy of Lt. Gov. Ralph S. Northam, the Democratic nominee for governor, Mr. Obama abandoned nine months of self-imposed political silence to accuse Ed Gillespie, the Republican, of fear-mongering tactics that he called “damaging and corrosive to our democracy.”

While not mentioning President Trump by name, Mr. Obama seemed to have the racially tinged 2016 presidential campaign on his mind as he denounced a controversial commercial that Mr. Gillespie has aired that targets the gang MS-13 — which has roots in Central America — and features a group of heavily tattooed Salvadoran prisoners.

“What he’s really trying to deliver is fear,” Mr. Obama said of Mr. Gillespie. “What he really believes is that if you scare enough voters, it might score just enough votes to win an election.”