Conservatives on the Supreme Court said Wednesday that it was unconstitutional to allow public employee unions to require collective-bargaining fees from workers who choose not to join the union, a major blow for the U.S. labor movement.

The court, in a 5-to-4 decision, overturned a 40-year-old precedent, arguing that the rule could require workers to give financial support to public policy positions they oppose.

“States and public-sector unions may no longer extract agency fees from nonconsenting employees,” Justice Samuel A. Alito Jr. wrote for the majority. “. . . This procedure violates the First Amendment and cannot continue.”

Justice Elena Kagan wrote for the dissenting liberals, objecting to a decision that she said would “wreak havoc” by undoing labor agreements throughout the country.

“There is no sugarcoating today’s opinion,” Kagan wrote. “The majority overthrows a decision entrenched in this Nation’s law — and in its economic life — for over 40 years. As a result, it prevents the American people, acting through their state and local officials, from making important choices about workplace governance.”

It was a devastating, if not unexpected, loss for public-employee unions, the most vital component of organized labor and a major player in Democratic Party politics. Major public-employee unions pour millions into independent campaigns, largely to bolster Democratic candidates up and down the ballot, and their members are steadfast participants in sophisticated get-out-the-vote efforts on Election Day.

Now their resources will be diminished. The nation’s largest teacher union, the National Education Association, said it could lose as many as 200,000 members this year and is preparing to cut about $28 million from its budget.

President Trump cast the decision as a political victory, tweeting: “Supreme Court rules in favor of nonunion workers who are now, as an example, able to support a candidate of his or her choice without having those who control the Union deciding for them. Big loss for the coffers of the Democrats!”

The ruling capped a years-long effort by conservative legal activists to forbid states from authorizing the fees. It is a major success for well-financed groups on the right such as the Koch network, which have battled public-employee unions in Wisconsin and other states.

The case concerns only public-sector unions, but union officials said that because those make up such a large percentage of the labor movement, the impact of the decision is great.

AFL-CIO President Richard Trumka said in a statement that the decision “abandons decades of common-sense precedent.” He added that “it will further empower the corporate elites in their efforts to thwart the aspirations of millions of working people standing together for a better life.”

Still, Randi Weingarten, president of the American Federation of Teachers, said the decision would not hinder the nascent teacher movements that led to walkouts this year in a half-dozen states such as West Virginia and Oklahoma.

“These walkouts are sending a signal to these judges that whether you strike down our legal rights or not, you can not strike down our voice,” Weingarten said.

The decision came on the term’s last day and was another example of how Trump’s selection of Neil M. Gorsuch to fill the seat of Justice Antonin Scalia, who died in 2016, refortified the conservative majority.

Joining Alito and Gorsuch in the opinion were Chief Justice John G. Roberts Jr. and Justices Clarence Thomas and Anthony M. Kennedy. It came just hours before Kennedy announced he would leave the court at the end of July, clearing the way for a further shift to the right.

Unions were already restricted from using the dues for political purposes such as support for candidates. But opponents of the mandatory fees say it is difficult to disentangle the two — raises for workers, for instance, might involve advocating for the government to raise taxes.

Challengers asked the court to overturn a 1977 decision, Abood v. Detroit Board of Education, that favored the unions. That ruling said states could allow public-employee unions to collect fees from nonmembers to cover the costs of workplace negotiations over salaries and benefits but not the union’s political activities.

The unions say losing fees from nonmembers will be a heavy blow because there is no incentive for workers to pay for collective-bargaining representation that they could get free. More than 20 states, including California, allow what the unions like to call “fair-share” fees intended to prevent nonmembers from getting a “free ride.”

Alito wrote that such concerns were not enough to overcome the First Amendment violation.

Nonmembers who may disagree with a union’s political positions, Alito said from the bench, say they are not free-riders but “captive riders,” because “they don’t want to make the trip at all.”

He also was unmoved by claims that the decision would be a crippling blow to the unions’ finances.

“We recognize that the loss of payments from nonmembers may cause unions to experience unpleasant transition costs in the short term,” Alito wrote. But he added, “It is hard to estimate how many billions of dollars have been taken from nonmembers and transferred to public-sector unions in violation of the First Amendment. Those unconstitutional exactions cannot be allowed to continue indefinitely.”

Kagan delivered part of her dissent from the bench, a fairly rare move for her. She and Alito sit next to each other, and she began just after he finished his summary of the decision.

Kagan broadly criticized the majority, which she said had overstepped its role by intervening in a political debate and “weaponizing” the First Amendment.

And “not for the first time,” she added, referring to the previous day’s 5-to-4 decision striking down a California law that required antiabortion pregnancy crisis centers to tell patients about the availability of state-offered services, including abortion.

“The majority’s road runs long. And at every stop are black-robed rulers overriding citizens’ choices,” she wrote in the dissent that was joined by Justices Stephen G. Breyer, Ruth Bader Ginsburg and Sonia Sotomayor. “The First Amendment was meant for better things. It was meant not to undermine but to protect democratic governance — including over the role of public-sector unions.”

The mention of “black-robed rulers” was borrowed from Scalia.

It was the third time the Roberts court had considered overturning Abood. It stopped short the first time but made clear it was open to the argument.

It appeared the challenge would be successful the next time the issue went before the court, in January 2016. But Scalia died a month later, and the court announced that it had split 4 to 4 on the issue.

Gorsuch provided the fifth vote.

In the case argued in 2016, the Obama administration supported the unions and said the court should abide by its precedent. But the Trump administration argued in favor of challengers at oral arguments in February.

The lead plaintiff in the new case, Mark Janus, a child-support specialist at the Illinois Department of Healthcare and Family Services, watched from the courtroom Wednesday seated next to Illinois Gov. Bruce Rauner (R).

The case is Janus v. AFSCME Council 31.

Moriah Balingit and Danielle Paquette contributed to this report.